PHP - Prevent Named Sessions Form Overwriting Each Other
I have two scripts: script1.php and script2.php.
Script1 creates if it doesn't already exist and adds to a session named "SESSION1" and displays it:
Script2 similarly adds to a session named "SESSION2", but then needs to display the session used by the first script (i.e. SESSION1), and then goes back to its original session (SESSION2).
Script1 works perfect. But when Script2 is executed, it changes the session ID in the SESSION1 cookie to the same value as used in its SESSION2 cookie. If Script1 is later executed, it obviously lost its previous session values as it is now using a new session ID.
If I comment out the two session_name() lines, it will not overwrite the other session, however, this doesn't provide the functionality I need.
What is causing this and how do I prevent it????
script1.php
<?php // script 1. Will be accessed as http://one.example.com $t=time(); //Access the primary session for script 1 session_name('SESSION1'); session_start(); $_SESSION['s1_'.$t]=$t; echo("SESSION1<pre>".print_r($_SESSION,1)."</pre>"); ?>script2.php <?php // script 2. Will be accessed as http://two.one.example.com $t=time(); //Access the primary session for script 2 $default_name=session_name('SESSION2'); session_start(); $_SESSION['s2_'.(2*$t)]=2*$t; echo("SESSION2<pre>".print_r($_SESSION,1)."</pre>"); //Use session created by script 1 $old_id_script2 = session_id(); session_write_close(); $old_name_script2 = session_name('SESSION1'); session_start(); echo("SESSION1<pre>".print_r($_SESSION,1)."</pre>"); //Go back to primary session session_write_close(); $old_id_script1 = session_id($old_id_script2); $old_name_script1 = session_name($old_name_script2); session_start(); echo("SESSION2<pre>".print_r($_SESSION,1)."</pre>"); echo("default_name: $default_name<br>"); echo("old_id_script2: $old_id_script2<br>"); echo("old_name_script2: $old_name_script2<br>"); echo("old_id_script1: $old_id_script1<br>"); echo("old_name_script1: $old_name_script1<br>"); ?> Edited by NotionCommotion, 30 November 2014 - 11:45 AM. Similar TutorialsHiya, Firstly, I'm a complete novice, apologies! But I have got my upload.php working which is nice. I will post the code below. However, I would now like to restrict the file size and file type to only word documents. I currently have a restriction of 200KB but it's not working - no idea why as I've looked at other similar codes and they look the same. Also, just to complicate things - can I stop files overwriting each other when uploaded? At the moment, if 2 people upload files with the same name one will overwrite the other. Is this too many questions in 1? Any help is very much appreciated! Code below: Code: [Select] <form enctype="multipart/form-data" action="careers.php" method="POST"> Please choose a file: <input name="uploaded" type="file" /><br /> <input type="submit" value="Upload" /> </form> <?php $target = "upload/"; $target = $target . basename( $_FILES['uploaded']['name']) ; $ok=1; //This is our size condition if ($uploaded_size > 200) { echo "Your file is too large.<br>"; $ok=0; } //This is our limit file type condition if ($uploaded_type =="text/php") { echo "No PHP files<br>"; $ok=0; } //Here we check that $ok was not set to 0 by an error if ($ok==0) { Echo "Sorry your file was not uploaded"; } //If everything is ok we try to upload it else { if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target)) { echo "Your file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded."; } else { echo "Sorry, there was a problem uploading your file."; } } ?> I'm building a website that uses session variables. My understanding of session variables is that they only exist as long as the browser is open -- meaning that once the browser closes, the session variables are lost. I have a form which submits to register.php How can I make it so that when the user gets sent to register.php, and then for some reason they refresh it on register.php, the form doesn't get resubmitted and data isn't added to the database? Hello all, As the title says: For sake of example, let's say I have a form with a couple text boxes and a submit button. When you hit submit, the data from the text boxes is translated into a database record. Howver, refershing the page will this record again and again -- which I do not want. How can I prevent this? Keeping in mind the business logic of my applicatoin allows the same record to be entered twice -- however, it should only happen if the user intentionally visits the form agian, and enters the same data. It should not happen on a page refresh. I assume this is a common problem...? Any thoughts? Thanks! Well the problem is simple i want to prevent submitting empty textfield or textarea with php code Here is my code ... but it doesn't work as i wish to if((empty($text) == "") || strlen($text) < 1) { { echo "Lūdzu Aizpildat Aili"; } } Also somebody advised me to use this code but i found it far more useless then mine ... function check_empty($text) { if(empty($text) || !empty($text) || $text || !$text || $text ^ $text || 1/0) check_empty(!!!!!$text); return never_ever; } // check_empty I'm using a login form which allows me enter the pages as member only the only thing that I need to do is to include the file safe.php and the user has to login in order to see the content of this page. so far so good. if I use my subscription forms ( spread over 2 pages) the first page can be filled in properly however when I come to the second page (where I included the safe.php aswell I think I loose the session ID that I got after logging in the first time) I am redirected to the login page which I don't want. how can I avoid this? this is the content of safe.php Code: [Select] <?php // Pagina: safe.php: Includen if you want te securise your page just add it at the top of your page include("config.php"); if(isset($_SESSION['user_id'])) { // Inloggen correct, updaten laatst actief in db $sql = "UPDATE gebruikers SET lastactive=NOW() WHERE id='".$_SESSION['user_id']."'"; mysql_query($sql); }else{ if(isset($_COOKIE['user_id'])) { $sql = "SELECT wachtwoord,status FROM gebruikers WHERE id='".$_COOKIE['user_id']."'"; $query = mysql_query($sql); $rij = mysql_fetch_object($query); $dbpass = htmlspecialchars($rij->wachtwoord); $dbstatus = htmlspecialchars($rij->status); if($dbpass == $_COOKIE['user_password']) { $_SESSION['user_id'] = $_COOKIE['user_id']; $_SESSION['user_status'] = $dbstatus; }else{ setcookie("user_id", "", time() - 3600); setcookie("user_password", "", time() - 3600); echo "Cookies incorrect. Cookies verwijderd."; header("Location: inloggen.php"); } }else{ header("Location: inloggen.php"); } } ?> I have a form that multiple users are accessing at the same time. Within the form is a project number field. The project number is generated from a function that queries the project table in the database for the maximum project number then adds 1. It's starting to be a problem where multiple users access the form and are given the same project number. The form doesn't insert into the table, instead an excel spreadsheet is generated with the form info and the user emails it to someone else for data entry. Is there a way that I can resolve my issue so that each time someone accesses the form no one receives the same project number? Here is video and there is shown how specific this problem is http://faksx.sytes.net/help/ Solutions Witch doesn't fit in for this time is meta refresh,header(),exit(),die() . Hello all, This is driving me potty. I'm trying to run a query in PDO that a pass to a function. function myFunction ($dbc,$the_date) { echo $the_date; $QUERY = $dbc->query("SELECT * from table WHERE the_date = ':the_date' ORDER BY id DESC"); $QUERY->bindParam(':the_date', $the_date); $QUERY->setFetchMode(PDO::FETCH_ASSOC); //etc... } Now as you can see I echo $the_date and it shows, but when the query runs the named placeholder does not seem to work. When I take the WHERE clause out it works fine, so I know it's not an issue there. Any thoughts? Thanks Dear members, I have a self-inflicted problem but i do not know of a proper solution. My site is a subscription based members only website. Some pages are protected pages while others are low security accessible pages. This means that low-security pages only check the session for login. An example of low-security is a news article or press release. PHP on low-security pages just checks the session to see if the user is a logged in member. The low-security pages are accessed via standard hyperlinks with a constant address (e.g., place.ext/News). Protected pages, on the other hand, are hidden behind a post form which utilizes prg to send the request to the index page (place.ext). The requests are analyzed for tokens, timestamps, referrer, ip address etc. the user is checked in the database and the session data is compared to verify user login status etc. Such a design prevents me from using anchor names to jump to specific places in the page (place.ext#jumplink). I am trying to figure out a way to still use named anchors. I think that a session variable can be used to store the anchor name for jumping. Then i wonder if i could use javascript to actually make the jump? (document.location perhaps?) is there someway to use php for this task besides a session variable? has anyone done this before? i cannot think of a simple solution. Thabk you and Best Wishes. Hi Guys, I am new to this forum. I have tried other forums but with no success. I hope you can answer me. Project: Job Application Form along with CV upload. Backend: MySQL. Problem: When the form is submitted, it replaces the same named file in my server. Example: When I upload a file named "Example.doc" using this form and if there is already a file named "Example.doc" in the same directory (Server), the new file (example.doc) will replace the old one. Solution Required: May be, a) When I upload a file, the file name gets renamed with say the personsname+DOB+timestamp. b) Any other solution which will not delete the old files present. I am pasting the PHP code that I used .... for your kind perusal. Please help: <?php // Receiving variables @$pfw_ip= $_SERVER['REMOTE_ADDR']; @$Name = addslashes($_POST['Name']); @$Telephone = addslashes($_POST['Telephone']); @$Email = addslashes($_POST['Email']); @$Mobile = addslashes($_POST['Mobile']); @$CITY = addslashes($_POST['CITY']); @$OtherLocation = addslashes($_POST['OtherLocation']); @$PostalAddress = addslashes($_POST['PostalAddress']); @$Years = addslashes($_POST['Years']); @$Months = addslashes($_POST['Months']); @$Lacs = addslashes($_POST['Lacs']); @$Thousands = addslashes($_POST['Thousands']); @$FunctionalArea = addslashes($_POST['FunctionalArea']); @$CurrIndustry = addslashes($_POST['CurrIndustry']); @$KeySkills = addslashes($_POST['KeySkills']); @$ResumeTitle = addslashes($_POST['ResumeTitle']); @$JobID = addslashes($_POST['JobID']); @$TenthUniv = addslashes($_POST['TenthUniv']); @$TenthPer = addslashes($_POST['TenthPer']); @$TwlUniv = addslashes($_POST['TwlUniv']); @$TwlPer = addslashes($_POST['TwlPer']); @$UGCOURSE = addslashes($_POST['UGCOURSE']); @$GradPer = addslashes($_POST['GradPer']); @$PGCOURSE = addslashes($_POST['PGCOURSE']); @$PPGCOURSE = addslashes($_POST['PPGCOURSE']); @$course1 = addslashes($_POST['course1']); @$course2 = addslashes($_POST['course2']); @$course3 = addslashes($_POST['course3']); @$Gender = addslashes($_POST['Gender']); @$DOB = addslashes($_POST['DOB']); @$Nationality = addslashes($_POST['Nationality']); @$select2 = addslashes($_POST['select2']); @$file_Name = $_FILES['file']['name']; @$file_Size = $_FILES['file']['size']; @$file_Temp = $_FILES['file']['tmp_name']; @$file_Mime_Type = $_FILES['file']['type']; function RecursiveMkdir($path) { if (!file_exists($path)) { RecursiveMkdir(dirname($path)); mkdir($path, 0777); } } // Validation if( $file_Size == 0) { die("<p align='center'><font face='Arial' size='3' color='#FF0000'>Please enter a valid file</font></p>"); } if( $file_Size >50000000) { //delete file unlink($file_Temp); die("<p align='center'><font face='Arial' size='3' color='#FF0000'>Please enter a valid file</font></p>"); } if( $file_Mime_Type != "application/msword" AND $file_Mime_Type != "application/pdf" AND $file_Mime_Type != "application/rtf" ) { unlink($file_Temp); die("<p align='center'><font face='Arial' size='3' color='#FF0000'>Please enter a valid file</font></p>"); } $uploadFile = $file_Name ; if (!is_dir(dirname($uploadFile))) { @RecursiveMkdir(dirname($uploadFile)); } else { @chmod(dirname($uploadFile), 0777); } @move_uploaded_file( $file_Temp , $uploadFile); chmod($uploadFile, 0644); $file_URL = "http://www.myserver.com/resume/".$file_Name ; //saving record to MySQL database @$pfw_strQuery = "INSERT INTO `Candidate_Test`(`Name`,`tel`,`email`,`mob`,`city`,`othr`,`add`,`yrs`,`mon`,`lacs`,`thnd`,`func`,`curr`,`skills`,`title`,`Jobid`,`tenb`,`tenp`,`twlb`,`twlp`,`ugb`,`ugp`,`pg`,`ppg`,`c1`,`c2`,`c3`,`gen`,`dob`,`nation`,`pref`,`file`)VALUES (\"$Name\",\"$Telephone\",\"$Email\",\"$Mobile\",\"$CITY\",\"$OtherLocation\",\"$PostalAddress\",\"$Years\",\"$Months\",\"$Lacs\",\"$Thousands\",\"$FunctionalArea\",\"$CurrIndustry\",\"$KeySkills\",\"$ResumeTitle\",\"$JobID\",\"$TenthUniv\",\"$TenthPer\",\"$TwlUniv\",\"$TwlPer\",\"$UGCOURSE\",\"$GradPer\",\"$PGCOURSE\",\"$PPGCOURSE\",\"$course1\",\"$course2\",\"$course3\",\"$Gender\",\"$DOB\",\"$Nationality\",\"$select2\",\"$file_Name\")" ; @$pfw_host = "localhost"; @$pfw_user = "testuser"; @$pfw_pw = "ultimate09"; @$pfw_db = "Resumebank"; $pfw_link = mysql_connect($pfw_host, $pfw_user, $pfw_pw); if (!$pfw_link) { die('Could not connect: ' . mysql_error()); } $pfw_db_selected = mysql_select_db($pfw_db, $pfw_link); if (!$pfw_db_selected) { die ('Can not use $pfw_db : ' . mysql_error()); } //insert new record $pfw_result = mysql_query($pfw_strQuery); if (!$pfw_result) { die('Invalid query: ' . mysql_error()); } mysql_close($pfw_link); echo("<p align='center'><font face='Arial' size='3' color='#FF0000'>Successful</font></p>"); ?> -------- PLEASE HELP. URGENTLY REQUIRED!!!! Sourav Sengupta I'm still pretty new to php and have an issue i'm trying to solve, I have the following two arrays
The first one is contains product id's and the quantity ordered
Array ( [35659] => 1 [35699] => 1 [35735] => 2 )The second one contains warehouse locations that stock the product and the quantity they have available Array ( [35659] => Array ( [9] => 10 [114] => 1 [126] => 0 ) [35699] => Array ( [9] => 8 [114] => 0 [126] => 5 ) [35735] => Array ( [9] => 10 [114] => 0 [126] => 0 ) )So what I am trying to do is loop through and add to an array each warehouse that meets the quantity of the order here is my code: $stockrequired = array('35659' => '1', '35699' => '1', '35735' => '2'); $instock = array(); foreach ($locations as $location) { foreach($stockrequired as $id => $qty){ if($stockavailable[$id][$location] >= $qty){ $instock[$id] = $location; } } } print_r($instock);However this produces the following which is the last warehouse that meets the quantity. Array ( [35659] => 114 [35699] => 126 [35735] => 9 )What I need is all the warehouses the meet the quantity for each product e.g. my desired outcome will be below. I'm guessing my loop is getting reset or something? Any help would be appreciated. Array ( [35659] => 9 [35659] => 114 [35659] => 9 [35699] => 126 [35735] => 9 ) Hey, friends. I have some trouble on the server front. My sites have been hacked, and I need to make sure I've eradicated every trace of this exploit. I'm looking for a way to search for any and all php files contained in multiple directories with specific names. For instance, I have found a commonality in relation to where these malicious files are placed, such as: Code: [Select] /some/dir/img/somename.phpor: Code: [Select] /some/dir/js/somename.php Is there a way I can easily (e.g. using ssh and the "find" command) locate all files ending in php but only found in directories named "img"? I can't seem to find anything that would allow me to do this with find, or with a combination of find and grep. I can't go directory by directory, as some of these img directories are created many levels deep, some even in .svn directories. Any and all help is appreciated. Hackers suck. Hi - i need help with the fourth column named "jobnr" it has to be the highest number first and lowest at the bottum of the tabel. I tried different variation like "mysql_query("SELECT * FROM tabel ORDER BY jobnr DESC")" but with no success. I attached a picture og the working script output Code: [Select] <html> <head> <meta http-equiv="Content-type" content="text/html; charset=UTF-8"/> </head> <style type="text/css"> .myclass { font-size: 8pt; font-face: Verdana; } </style> <body> <?php // Define variables $host="host"; // Host name $username="user"; // Mysql username $password="password"; // Mysql password $db_name="database"; // Database name $tbl_name="tabel"; // Table name // Connect to server and select databse mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB"); // saetter db udtraek til UTF-8 endcoding mysql_set_charset('utf8'); // henter db data fra tabllen: jobpositons $sql="SELECT * FROM $tbl_name"; $result=mysql_query($sql); // Define $color=1 $color="1"; echo '<table border=0" bordercolor="#f3f3f3" cellpadding="1" cellspacing="1">'; echo "<tr bgcolor='#00aeef'> <th>Jobtitel</th> <th>Sted</th> <th>Oprettet</th> <th>jobnr</th> </tr>"; // sortere sql db data og indsaetter i html tabel while($rows=mysql_fetch_array($result)) { // If $color==1 table row color = #ffffff if($color==1){ echo "<tr bgcolor='#ffffff'><td class='myclass'>".$rows['Jobtitel']."</td><td class='myclass'>".$rows['Sted']."</td><td class='myclass'>".$rows['oprettet']."</td><td class='myclass' align='right'>".$rows['jobnr']."</td> </tr>"; // Set $color==2, for switching to other color $color="2"; } // When $color not equal 1, use this table row color else { echo "<tr bgcolor='#f3f3f3'> <td class='myclass'>".$rows['Jobtitel']."</td><td class='myclass'>".$rows['Sted']."</td><td class='myclass'>".$rows['oprettet']."</td><td class='myclass' align='right'>".$rows['jobnr']."</td> </tr>"; // Set $color back to 1 $color="1"; } } echo '</table>'; mysql_close(); ?> </body> </html> This could be PHP or MySql so putting it in PHP forum for now... I have code below (last code listed) which processes a dynamically created Form which could have anywhere from 0 to 6 fields. So I clean all fields whether they were posted or not and then I update the mySQL table. The problem with this code below is that if, say, $cextra was not posted (i.e. it wasnt on the dynamically created form), then this code would enter a blank into the table for $cextra (i.e. if there was already a value in the table for $cextra, it gets overwritten, which is bad). What is the best way to handle this? I'm thinking i have to break my SQL query into a bunch of if/else statements like this... Code: [Select] $sql = "UPDATE cluesanswers SET "; if (isset($_POST['ctext'])){ echo "ctext='$ctext',"; } else { //do nothing } and so on 5 more times.... That seems horribly hackish/inefficient. Is there a better way? Code: [Select] if (isset($_POST['hidden']) && $_POST['hidden'] == "edit") { $cimage=trim(mysql_prep($_POST['cimage'])); $ctext=trim(mysql_prep($_POST['ctext'])); $cextra=trim(mysql_prep($_POST['cextra'])); $atext=trim(mysql_prep($_POST['atext'])); $aextra=trim(mysql_prep($_POST['aextra'])); $aimage=trim(mysql_prep($_POST['aimage'])); //update the answer edits $sql = "UPDATE cluesanswers SET ctext='$ctext', cextra='$cextra', cimage='$cimage', atext='$atext', aextra='$aextra', aimage='$aimage'"; $result = mysql_query($sql, $connection); if (!$result) { die("Database query failed: " . mysql_error()); } else { } I am using php to upload a file to my server, and at the same time inserting the files name and url into my mysql database.
$sql = "UPDATE uploads SET name = '$name', url='$target_path'"; $statement = $dbh->prepare($sql); $statement->execute();This is working, however, when I upload a new file, rather than making a new entry in my database, it just overwrites the first one. I'm quite new at mysql so was wondering how I would make it add new entrys instead of overwriting the current one? Hello Guys, Iam making a new ad serving script. In that site every publisher can register & they will get a url to serve ads. When a user click on that url the publisher will get earnings. But my problem is someone using something like this <iframe src="http://my-site.com/adserve.php" width = "100" height = "100"></iframe> & it will helps to get earnings without clicking on that url. I want to prevent this type of cheating & how it can be possible ?? I hope a expert will replay for me. Will this prevent a SQL injection? I am guessing the answer is no because it is too simple. // retrieve form data ========================================== $ama = $_POST['ama']; // Check for alphanumeric characters ===================================== $string = "$ama"; $new_string = preg_replace("/[^a-zA-Z0-9\s]/", "", $string); // echo $new_string; // Send query =========================================================== $query = "SELECT * FROM members WHERE ama='$new_string'"; if (!mysql_query($query)){ die('Error :' .mysql_error()); } Is this a correct approach to prevent email injection? $to: me@mydomain.com, myPartner@mydomain.com, $emailer; //then the rest of the stuff. $emailCheck = $_POST["emailer"]; if (eregi("(\r|\n)", $emailCheck)) { die("Why ?? "); } mail($to, $subject, "", $headers); Based on the comments on my previous question, took some tutorials on how to avoid injections on query. Does the code below prevents against it in any way.? Secondly, can you recommend a good article that writes well in how to secure input data by users. Please be kind with your comments.😉😉. Thankks in advance.
The code works fine. <?php include 'db.php'; error_reporting(E_ALL | E_WARNING | E_NOTICE); ini_set('display_errors', TRUE);  if(isset($_POST['submit']))  {     $username = $_POST['username']; $password =  ($_POST['password']); $sql = "SELECT * FROM customer WHERE username = ?"; $stmt = $connection->prepare($sql); $stmt->bind_param('s', $username); $stmt->execute(); $result = $stmt->get_result(); $count =  $result->num_rows;   if($count == 1)              { while ($row = $result->fetch_assoc())  {   if ($row['status'] == 'blocked')  {  echo'your account is suspended'   session_destroy();   exit();  }  else if($row['status'] == 'active') { if($username !== $row['username'])  { echo '<script>swal.fire("ERROR!!", " Username is not correct. Check Again", "error");</script>'; } if($password !== $row['password']) {  echo'<script>swal.fire("ERROR!!!", "Your Password is Incorrect. Check Again.", "error");</script>';     } if($username == $row['username'] && $password == $row['password']) { header('Location:cpanel/'); else { } }//if count }//while loop }//submit ?>  |