alex3 Posted August 5, 2009 Share Posted August 5, 2009 Hullo. I have a nice little login system up and running that uses sessions. The inconveniences for sessions are known, so I'd to add a 'Remember me' style checkbox, and have PHP set a cookie if checked. My problem is that I don't know how to integrate a cookie system in to what I've got. Here's my current login script (it's called via an AJAX request, if the JavaScript receives yes, it redirects to the members-only page, if no it throws an error): <?php session_start(); //If the form has been submitted take the values POSTed and prevent MySQL injection if (isset($_POST['username']) && isset($_POST['password'])) { foreach ($_POST as $key => $value) { $_POST[$key] = trim(stripslashes($value)); } //Hash password and create variables from user field and hashed password $enc_password = md5($_POST['password']); $username = $_POST['username']; // Get MySQL database details //include '../includes/db.php'; include '../includes/config.php'; //Select DB //mysql_select_db($db_name, mysql_connect($host, $dbusername, $dbpassword)) or die(mysql_error()); mysql_select_db(DB_NAME, mysql_connect(DB_HOSTNAME, DB_USERNAME, DB_PASSWORD)) or die(mysql_error()); // Select table and query for matching entry $sql = mysql_query("SELECT * FROM members WHERE username='$username' and password='$enc_password'") or die(mysql_error()); // Set a variable of the returned row $row = mysql_fetch_array($sql); $err = null; // If there is no row to be selected, $row is null so create error variable if (!$row) { $err = "Wrong username/password."; } // If there is a row, create a session and echo yes else { $_SESSION['loggedin']['user'] = $_POST['username']; echo "yes"; } } // End if // If the $err variable is not empty (i.e. if there is an error), echo no if (!is_null($err)) { echo "no"; } And here's the code placed at the top of every page to be protected: <?php session_start(); // Checks that the user is logged in and redirects if not if (!isset($_SESSION['loggedin']['user'])) { header("location:./login/"); } else { $currentuser = $_SESSION['loggedin']['user']; } // If the URL has ?logout, log the user out. if(isset($_GET['logout'])){ session_destroy(); header("location:./login/"); } include 'includes/config.php'; ?> Using cookies, would I have to check for a session that has been set, and then if that doesn't exist look for a cookie? Should I set a cookie and start the session? What information should I be setting in the cookie? I'm not sure on the little details. Quote Link to comment https://forums.phpfreaks.com/topic/168927-adding-cookie-support-to-an-existing-sessions-based-login-system/ Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.