PHP - Having Problem While Storing Data In Sessions & Cookies
I have created a login form. I am sending values through Ajax for form validation. However, I am having problem with the code that I am unable to store values in Sessions & Cookies.
I have added a "Remember me" checkbox into login form. I want to validate Boolean value using Javascript Checked property and send the data to PHP for validation.
If user clicks on remember me checkbox then the data should be stored in either Sessions & Cookies. If it is not checked then data should be stored only in Sessions. I am posting here my login form code, Ajax code & PHP code.
Could you guys help me to point out my mistake what I am doing wrong in this code?
Login Form:
<input type="checkbox" id="cb" name="cb"> <label for="cb">Remember me</label>Ajax Code: function login(){var e = _("email").value; var pass = _("password").value; var cb = _("cb").value; if(e == "" || pass == ""){ _("status").innerHTML = "Please fill out the form"; } else { _("loginbtn").style.display = "none"; _("status").innerHTML = 'please wait ...'; var ajax = ajaxObj("POST", "handlers/login_handler.php"); ajax.onreadystatechange = function() { if(ajaxReturn(ajax) == true) { if(ajax.responseText == "login_failed"){ _("status").innerHTML = "Login failed, please try again."; _("loginbtn").style.display = "block"; } else { window.location = "message.php?msg=Hello "+ajax.responseText; } } } ajax.send("e="+e+"&pass="+pass+"&cb="+cb); } }PHP Code: $cb = cleanstr($_POST['cb']); if(isset($cb) && ($cb == true)) { // IF USER CLICKED ON REMEMBER ME CHECKBOX CREATE THEIR SESSIONS AND COOKIES $_SESSION['userid'] = $db_id; $_SESSION['username'] = $db_username; $_SESSION['password'] = $db_pass; setcookie("id", $db_id, strtotime( '+30 days' ), "/", "", "", TRUE); setcookie("user", $db_username, strtotime( '+30 days' ), "/", "", "", TRUE); setcookie("pass", $db_pass, strtotime( '+30 days' ), "/", "", "", TRUE); // UPDATE THEIR "IP" AND "LASTLOGIN" FIELDS $sql = "UPDATE users SET ip='$ip', lastlogin=now() WHERE id='$db_id' LIMIT 1"; $query = mysqli_query($con, $sql); echo $db_username; exit(); } else { // IF USER HAS NOT CLICKED ON REMEMBER ME CHECKBOX CREATE THEIR SESSIONS ONLY $_SESSION['userid'] = $db_id; $_SESSION['username'] = $db_username; $_SESSION['password'] = $db_pass; // UPDATE THEIR "IP" AND "LASTLOGIN" FIELDS $sql = "UPDATE users SET ip='$ip', lastlogin=now() WHERE id='$db_id' LIMIT 1"; $query = mysqli_query($con, $sql); echo $db_username; exit(); } Similar TutorialsI am having some problems with part of the code. What is going on is a user registers info with a form and is sent an email with a confirmation link. The info that was in a temp DB table is moved to a member table. All of this works fine, but I am trying to be able to store an ID and username associated with their passkey info and echo that variable out. This part I am having trouble with. Code is here. <? session_start(); include('config.php'); // Passkey t from link $passkey=$_GET['passkey']; $tbl_name1="Profile_temp"; // Retrieve data from table where row matches passkey $sql1="SELECT * FROM $tbl_name1 WHERE confirm_code ='$passkey'"; $result1=mysql_query($sql1); // If successfully queried if($result1){ // Count how many row has this passkey $count=mysql_num_rows($result1); // if passkey is found retrieve info from temporary DB if($count==1){ $rows=mysql_fetch_array($result1); $FirstName=$rows['FirstName']; $LastName=$rows['LastName']; $UserName=$rows['UserName']; $Password= md5($rows['Password']); $Password2=md5($rows['Password2']); $email=$rows['email']; $Zip=$rows['Zip']; $Birthday=$rows['Birthday']; $Security=$rows['Security']; $Security2=$rows['Security2']; $tbl_name2="Profile"; // Insert data that retrieves from "temp_members_db" into table "registered_members" $sql2="INSERT INTO $tbl_name2(`FirstName`,`LastName`,`Username`,`Password`,`Password2`,`email`,`Zip`,`Birthday`,`Security`,`Security2`) VALUES ('$FirstName','$LastName','$UserName','$Password','$Password2','$email','$Zip','$Birthday','$Security','$Security2')"; //echo $sql2; $result2=mysql_query($sql2); } // if passkey is not found, display message "Wrong Confirmation code" else { echo "<h2>Sorry, Your passkey was not found.</h2>"; } while ($row = mysql_fetch_assoc($result2)) { $_SESSION['id'] = $row['id']; $_SESSION['UserName']=$user_name; } // if successfully moved data from table"temp_members_db" to table "registered_members" displays message "Your account has been activated" and don't forget to delete confirmation code from table "temp_members_db" if($result2){ echo "<h2>Your account has been activated, </h2>"; echo "$user_name"; echo"<p>You may now upload a profile picture</p>"; // Delete information of this user from table "temp_members_db" that has this passkey $sql3="DELETE FROM $tbl_name1 WHERE confirm_code = '$passkey'"; $result3=mysql_query($sql3); } } ?> getting an error for this part while ($row = mysql_fetch_assoc($result2)) { $_SESSION['id'] = $row['id']; $_SESSION['UserName']=$user_name; } the error is "Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in confirmation.php on line 62" Hello everyone I wonder if you could help me. I want to create a function called <?php function mythings($what) Which would allow me to pass an ID number to, such as <?php mythings(5419); What I want to do with that function is store the ID numbers of the past 6 items I have viewed, but I want to store each item as a SESSION once it has been passed. So essentially I would end up with the following 6 SESSIONS <?php $_SESSION['item1']; $_SESSION['item2']; $_SESSION['item3']; $_SESSION['item4']; $_SESSION['item5']; $_SESSION['item6']; So the "item1" SESSION would be the latest item ID passed through the function But then if I then passed a new ID through the function, that new ID passed would then become $_SESSION['item1']; and the current SESSION $_SESSION['item1']; would become $_SESSION['item2']; and $_SESSION['item2']; would become $_SESSION['item3']; and so on. This means I can do a list such as <?php print "Item 1".$_SESSION['item1']."<br>"; print "Item 2".$_SESSION['item2']."<br>"; print "Item 3".$_SESSION['item3']."<br>"; print "Item 4".$_SESSION['item4']."<br>"; print "Item 5".$_SESSION['item5']."<br>"; print "Item 6".$_SESSION['item6']."<br>"; ?> Does that make much sense? Can anyone help. Thanks very much all John I'm creating a login. When a user logs in, they can choose for the website to remember them. If they do, then the login function creates cookies. The function checks the database for the information and then stores it into an array and creates the cookies. HOWEVER when a user doesn't choose for the website to remember them, then I assume I will be using session variables. However, I am not sure how to go about it. Usually, I would create a cookie for the username and the password. Would it be safe to create session variables for the username and password to last for the session and then use these? I'm just confused how to deal with just a session.. I have attached a very simple remember me script. Could someone please have a look at it and tell me if I'm doing it correctly, or what the correct implementation would be to allow users to not use and use the remember me function? I'm trying to learn the proper workaround to enable Sessions when visitors have their cookies disabled.
When I create a PHP session page with ini_set("session.use_trans_sid", 1) and then disable my browser cookies and view browser source code, I see what I expect: a hidden input appended like this: It seems to work (sessions without cookies!). However, I don't see the long URL query strings that I used to see when I experimented with this 10 years ago, and I don't see the long PHPSESSID value appended to all the page links, and I don't see dozens of session variables appended as hidden form inputs. Rather, I just see the one PHPSESSID hidden input described above. Is this because all the session variables are stored on the server itself, and all the server needs is that one single long PHPSESSID value? Or, am I doing it wrong? :-) Edited April 4, 2019 by StevenOliver Hi guys, I want a PHP Cookie & Session to apply to both the domain and all its subdomains, except one specific subdomain which I never want the same cookies/sessions to apply to. I have the apply too all sorted, just not the exception. Any help is much appreciated. I'm brushing up on Cookies and Sessions. My book says that in order to access the same Session data, you must have Code: [Select] session_start(); on each page that uses the Session data AND the user must have accepted the Session Cookie?! So what do you do if a user has Cookies Turned Off or Declines a Session Cookie?? (I find it hard to believe that Sessions are that "delicate"?!) TomTees Hi, I want to end a session when a registered user is asked to login again but enters the incorrect credentials. I'm destroying the session and taking the user back to the login page, but for some reason when s/he clicks "back" on the browser s/he is able to get back into her/his account. Any ideas? I am having a hard time getting sessions and cookies to work as I would expect. I am using codelobster editor/debugger and wampserver. My problem is that when I try to delete a cookie it shows that the cookie is still there and active. <?PHP session_start(); date_default_timezone_set('Asia/Qatar'); // I try to delete the previous cookie which was set setcookie('my_session',"",time()-3600); // here I have a function that sets a cookie log_session("username","password"); session_destroy(); ?> When I check the local variables in the debugger they are still there and not deleted and have the same value. Is my logic wrong or is it my system? Hello , my website uses sessions to check for users if they are logged in, get data and such stuff.. But i want to add cookies in order to make users stay logged in for more time.. I do have a remember me checkbox and a function that tells me if a user is loggedin by checking if session or cookie is set and then it returns a true flag... the problem is that i dont know how to get if he is logged via session or cookies Thanks. I am using the scripts (at the end) on a shared debian server at my web host's remote facility. I'm very new to PHP and have been working on my site idea for the past couple of weeks and have been working on the basic sign up, logging in, activation and log out. The log out works fine, but when I sign in with a second username, the first user name's information comes up instead. Here's the log out script: <?php session_start(); session_unset(); session_destroy(); setrawcookie('user'); ?> I tried a bunch of other stuff but nothing seems to work. Closing the window and stuff works fine but obviously, that's not the safest method. I need advice on how to handle a php issue. I will try to simply my problem as best as I can. Index.php is used to upload multiple pictures engine.php is called each time for each picture. So if someone uploads 3 pictures engine.php is called 3 times and uploads each picture separately. What I want to be able to do is to track bulk uploads. For example, if someone uploads 10 pictures at once there would be a unique code in my database that I could query and see the results of the 10 pictures that where uploaded. Kinda like a batch. The problem is that I can't seem to create a unique code that it's used to to track batches. I have used cookies in my index.php and set it to a random variable. When my engine.php starts uploading images via POST method, it calls the cookie that was stores in index.php only to see that the value doesn't get passed. I check index.php by using echo $_COOKIE['...']; and a value does get into the cookie, but engine.php can't seem to access the cookie. (I used setcookie) Here's part of the code for the cookies (engine.php): $getmu = $_COOKIE['multiupload']; $insert_image = "INSERT INTO images (owner, dateadded, mimetype, originalfilename, filename, thumbname, filesize, description, originalip, originalwidth, originalheight, lastaccessed, tracker, mutracker) VALUES ($displayID, NOW(), '".preparedata($contenttype)."', '".preparedata($filename)."', '".preparedata($newfilename)."', '".preparedata($ranthumb)."' , '".preparedata($filesize)."', '".preparedata($imgdesc)."', '".preparedata($userip)."', '".$originalwidth."', '".$originalheight."', NOW(), '".preparedata($tracker)."', '".$getmu."')"; if I set $getmu to just any string, it seems to get inserted into the db, so it's not a syntax issue. When I use cookies, nothing gets inputed. I also tried using sessions, but since engine.php is called for each picture upload, the session changes for every picture. Any ideas or advice? I'm kinda stuck on this. The cookies should work, but they don't :/ Hello, On my site I offer the option an option for cookies or sessions on login. If a remember me box is selected, then a cookie will be set. My question is, how do I assign both the $_SESSION['id'] and $_COOKIE['id'] to the same variable? Thanks for the help! Hello again, I posted a question earlier about an include issue which I managed to fix but now I am dealing with a completely new error message and unlike before I don't even have a basic Idea of what is going on. The error in question is - Quote An error occurred in script 'C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\IUS\Login\form_process.php' on line 10: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\IUS\Index.php:1) Date/Time: 1-10-2012 16:49:31 the code for form_process.php is as follows Code: [Select] <?php # Script 16.8 - login.php // This is the login page for the site. require_once ('login/config2.inc.php'); // Start output buffering: ob_start(); // Initialize a session: session_start(); if (isset($_POST['submitted'])) { require_once (MYSQL); // Validate the email address: if (!empty($_POST['email'])) { $e = mysqli_real_escape_string ($dbc, $_POST['email']); } else { $e = FALSE; } // Validate the password: if (!empty($_POST['pass'])) { $p = mysqli_real_escape_string ($dbc, $_POST['pass']); } else { $p = FALSE; } if ($e && $p) { // If everything's OK. // Query the database: $q = "SELECT user_id, first_name, user_level FROM users WHERE (email='$e' AND pass=SHA1('$p')) AND active IS NULL"; $r = mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc)); if (@mysqli_num_rows($r) == 1) { // A match was made. // Register the values & redirect: $_SESSION = mysqli_fetch_array ($r, MYSQLI_ASSOC); mysqli_free_result($r); mysqli_close($dbc); $url = BASE_URL . 'index.php'; // Define the URL: ob_end_clean(); // Delete the buffer. header("Location: $url"); exit(); // Quit the script. } else { // No match was made. echo '<p class="error">Either the email address and password entered do not match those on file or you have not yet activated your account.</p>'; } } else { // If everything wasn't OK. echo '<p class="error">Please try again.</p>'; } mysqli_close($dbc); } // End of SUBMIT conditional. ?> The process also uses config2.php so I am including the code for that in-case it helps Code: [Select] <?php # Script 16.3 - config.inc.php // ********************************** // // ************ SETTINGS ************ // // Flag variable for site status: define('LIVE', FALSE); // Admin contact address: define('EMAIL', 'email@gmail.com'); // Site URL (base for all redirections): define ('BASE_URL', 'localhost/IUS'); // Location of the MySQL connection script: define ('MYSQL', 'login/mysqli_connect.php'); // Adjust the time zone for PHP 5.1 and greater: date_default_timezone_set ('US/Eastern'); // ************ SETTINGS ************ // // ********************************** // // ****************************************** // // ************ ERROR MANAGEMENT ************ // // Create the error handler: function my_error_handler ($e_number, $e_message, $e_file, $e_line, $e_vars) { // Build the error message. $message = "<p>An error occurred in script '$e_file' on line $e_line: $e_message\n<br />"; // Add the date and time: $message .= "Date/Time: " . date('n-j-Y H:i:s') . "\n<br />"; // Append $e_vars to the $message: $message .= "<pre>" . print_r ($e_vars, 1) . "</pre>\n</p>"; if (!LIVE) { // Development (print the error). echo '<div class="error">' . $message . '</div><br />'; } else { // Don't show the error: // Send an email to the admin: mail(EMAIL, 'Site Error!', $message, 'From: you@youremail.com'); // Only print an error message if the error isn't a notice: if ($e_number != E_NOTICE) { echo '<div class="error">A system error occurred. We apologize for the inconvenience.</div><br />'; } } // End of !LIVE IF. } // End of my_error_handler() definition. // Use my error handler. set_error_handler ('my_error_handler'); // ************ ERROR MANAGEMENT ************ // // ****************************************** // ?> At first I thought it was because cookies weren't enabled but I am positive they are, so I am really at a loss as-to what's going on, there is more to the error message, though its quite long and will take me a few minutes to go through and remove/alter any sensitive information. I am about to attempt to write my first php script from scratch after a year or so of copying and adapting code. I am going to do a registration/login in system and thinking ahead, want to make sure that once someone is logged in, this information is passed from page to page (so they do not have to log in again on each page) and I would also like to provide a 'Remember Me' option. I have had a read up and from what I gather, sessions would be better for showing someone is logged in from page to page and cookies would be the only way to implement a 'Remember Me'. Would this be the best way to approach this or is/are there better ways? Thanks in advance Steve after authenticating username and password,i have a parameter like: $_SESSION['logged']=1 should i be storing this as a cookie?..if yes, then can anyone modify cookie, to have this parameter as "1", and gain access? I have two files with coding in. One of them is the HTML form file: Code: [Select] <?php <html><head><title>Car Accident Program</title></head> <body> <!----In this block of code I am creating a form with 4 text boxes and a button as well as user prompts to get user inputted values to work with----> <h4>Car Accident Report Form</h4> <form action="Car.php" method="post"> <b>First Name:<b><br> <input type="text" size = "45" name="firstname"><br> <b>Surname:<b><br> <input type="text" size = "45" name="surname"><br> <b>Age:<b><br> <input type="text" size = "45" name="age"><br> <b>Number of weeks since accident:<b><br> <input type="text" size = "45" name="weeks"><br> <input type="submit" value="Submit report"> </form> </body> </html> and the PHP/Validation file: Code: [Select] <!----In this block of code, I am creating a PHP script that gets the user inputted values and can display them in a report as well as use an IF statement to show an extra line to appear if the user enters an age below 18 or a time since accident below 1 week or if they miss out a field or more----> <?php $firstname= $_POST ['firstname']; $surname =$_POST ['surname']; $age=$_POST ['age']; $weeks=$_POST ['weeks']; //Here, I am providing various paths and the outcomes in a PHP script if (empty($_POST['firstname']) or empty($_POST['surname']) or empty($_POST['age']) or empty($_POST['weeks'])) {$msg= "You missed out one or more fields. Click on the link below to go back to the form and enter information into all of the fields";} else if (is_numeric($age) && $age<0) {$msg="You cannot be under 0 years of age";} else if (is_numeric($weeks) && $weeks<0) {$msg="The number of weeks since an accident cannot be below 0";} else if (is_numeric($age) && $age>0 && $age<18) {$msg= "You are too young to file an accident report";} else if (is_numeric($weeks) && $weeks<2) {$msg= "You cannot file an accident report that happened less than two weeks ago";} else { setcookie(" $msg= "First Name: $firstname<br>"; $msg .="Surname: $surname<br>"; $msg .= "Age: $age<br>"; $msg .="Number of weeks since accident: $weeks<br>"; $msg .="Your report has been accepted. Please click on the link below to go back to the Accident Report Page";} echo ($msg) ?> </body> </html> <html> <a href="http://localhost/Car.htm"><br><br>Click here to add/edit an Accident Report</a> I was wondering how, if suitable, I would add a cookie or session into coding like this. Any help is appreciated, Andrew I am trying to build my own custom login script. What I am trying to achieve is once a user has logged in depending on wether they have checked the keep me logged in checkbox they have two options. If they haven't checked it then it creates session variables only, and if they have checked it it also creates cookie variable as well as the session variables. If they then close their browser / tab without logging out and then revisit the site they will get redirected to login page because the active session variable is no longer there. As soon as they land on the loggin page, it automatically checks for the cookie variable and if it exists, it uses it to login and redirect them automatically. However the problem that I am facing is that the session variable is still being trashed after a default amount of idle time and forcing a login. My goal is that the user shouldn't have to re-login unless they have either clicked the logout button. Can someone please have a look through my solution and advise me as to wether this is the correct method that I am implementing, if there is an easier way to achieve what I want, and is this a secure way to handle user logins. Thanks in advance. Andrew Here is the check code I have placed at the top of each admin page. Code: [Select] <?php session_start(); $url = (!empty($_SERVER['HTTPS'])) ? "https://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'] : "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']; $uid = $_SESSION['uid']; if (!isset($uid)) { header('location:login.php?redirect='.$url); exit(); } ?> Next we have the code for the login.php file. Code: [Select] <?php include ('functions.php'); ?> <?php get_header('login'); ?> <div id="login-result"> <?php connect(); $redirect = htmlspecialchars(mysql_real_escape_string(addslashes($_GET['redirect']))); if(isset($_COOKIE['remembered'])){ $username = htmlspecialchars(mysql_real_escape_string(addslashes($_COOKIE['remembered']['username']))); $password = htmlspecialchars(mysql_real_escape_string(addslashes($_COOKIE['remembered']['password']))); $sql = "SELECT * FROM usersT WHERE username='$username' AND password='$password'"; $result = mysql_query($sql); $count = mysql_num_rows($result); $row = mysql_fetch_array($result); $uid = $row['uid']; $fname = $row['firstname']; $lname = $row['lastname']; $role = $row['role']; if($count==1){ $sql2 = "UPDATE usersT SET status = '1' WHERE uid = '$uid'"; $result2 = mysql_query($sql2); if($result2){ session_register("uid"); session_register("uname"); session_register("ulevel"); $_SESSION["uid"] = $uid; $_SESSION["uname"] = $fname; $_SESSION["ufullname"] = $fname . " " .$lname; $_SESSION["urole"] = $role; $home = get_option('home'); if(!empty($redirect)) { header( 'Location: '. $redirect ) ; exit(); } else { header( $home ) ; exit(); } } } else { echo "<div class=\"error rounded5 shadow\">Invalid username or password!</div>"; } } else if (isset($_POST['admin_login'])){ if(isset($_POST["username"]) && isset($_POST["password"])){ $username_p = htmlspecialchars(mysql_real_escape_string(addslashes($_POST["username"]))); $password_p = htmlspecialchars(mysql_real_escape_string(addslashes($_POST["password"]))); $psw = md5($password_p); $sql3 = "SELECT * FROM usersT WHERE username='$username_p' AND password='$psw'"; $result3 = mysql_query($sql3); $count3 = mysql_num_rows($result3); $row3 = mysql_fetch_array($result3); $uid = $row3['uid']; $fname = $row3['firstname']; $lname = $row3['lastname']; $role = $row3['role']; if($count3==1){ $sql4 = "UPDATE usersT SET status = '1' WHERE uid = '$uid'"; $result4 = mysql_query($sql4); if($result4){ session_register("uid"); session_register("uname"); session_register("ulevel"); $_SESSION["uid"] = $uid; $_SESSION["uname"] = $fname; $_SESSION["ufullname"] = $fname . " " .$lname; $_SESSION["urole"] = $role; $home = get_option('home'); if(isset($_POST['remember'])) { setcookie("remembered[username]", $username, time() + 86400 * 365 * 2); setcookie("remembered[password]", $psw, time() + 86400 * 365 * 2); } if(!empty($redirect)) { header( 'Location: '. $redirect ) ; exit(); } else { header( $home ) ; exit(); } } } else { echo "<div class=\"error rounded5 shadow\">Invalid username or password!</div>"; } } } ?> </div><!-- / login-results --> <div id="login" class="rounded5 shadow"> <form name="loginform" id="loginform" action="<?php $_SERVER['PHP_SELF']; ?>" method="post"> <p> <label for="username">Username<br> <input type="text" name="username" id="username" class="rounded5" value="<?php echo $username_p; ?>" size="20" tabindex="10" /></label> </p> <p> <label for="password">Password<br> <input type="password" name="password" id="password" class="rounded5" value="<?php echo $password_p; ?>" size="20" tabindex="20" /></label> </p> <p class="submit"> Keep me logged in<input type="checkbox" name="remember" id="remember" /><br /><br /><a href="" class="left">Lost your password?</a> <input type="submit" name="admin_login" id="admin_login" class="btn rounded10 right" value="Log In" tabindex="100" /> </p> <div class="cleaner"></div><!-- / cleaner --> </form> </div><!-- / login--> <?php get_footer('login'); ?> Finally here is the code I am using for the logout.php page. Code: [Select] <?php session_start(); include ('functions.php'); connect(); $uid = mysql_real_escape_string($_SESSION['uid']); $sql = "UPDATE usersT SET status = '0' WHERE uid = '$uid'"; $result = mysql_query($sql); if($result) { session_unset(); session_destroy(); if(isset($_COOKIE['remembered'])){ setcookie("remembered[username]", $username, time() - 3600); setcookie("remembered[password]", $psw, time() - 3600); header("location: login.php"); } exit(); } else { echo "You couldn't be logged out at this time."; } ?> |