Php – Cookies PHP

cookiesPHP

How would I "build-in" an autologin to this script?

if (isset($_POST['login'])) {
$query = mysql_query("
          SELECT * FROM users 
          WHERE user_name = '".mysql_real_escape_string($_POST['username'])."' 
      AND user_password = '".mysql_real_escape_string($_POST['password'])."'
");

/* wrong login information? terminate the script */
if (!mysql_num_rows($query)){
header("Location: ./");
exit();
}

/* set session with unique index */
$_SESSION['id'] = mysql_result($query, 0, 'user_id');
mysql_query("UPDATE users SET user_online = '1' WHERE user_id = '{$_SESSION['id']}'");
header("Location: ./");
exit;
}

Best Answer

First, some suggestions:

  1. You should store the passwords as salted hashes, not as plaintext.
  2. You might want to change the way you do authentication in general. It might be a good idea to select the password (don't do "Select *" anyway) and compare it to the salted hash of the password the user typed in.

Now, you're asking, if I understand correctly, how to keep the user logged in. The basic idea is that you need to store a cookie with something that uniquely identifies the user (but make sure it is not something that be easily hijacked - so make it a really long string, like a SHA1 hash or something.) Set a far away expiration date on the cookie to keep the user logged in.

Here is the function you use to set cookies in PHP.

Then, when you load the page, you can check to see if that cookie exists. If the cookie exists, and the user does not have a SESSION variable, you can assign him one.