[thelist] Remember Me Option -Cookies

Gijs van Tulder evolt at gmx.net
Tue Feb 11 16:06:01 CST 2003


Mark,

> -----Original Message-----
> From: Mark Joslyn
> Subject: RE: [thelist] Remember Me Option -Cookies

> I am having trouble tying the code to the "Remember Me" checkbox.
> Also, when do I write the cookie, when do I get the value of the
> cookie, and how do I populate the username and password fields
> with the cookie info when the checkbox is "checked"??? Are all
> these things tied to the "Login" or Submit button. All questions
> I need help with!!!
>
> I am using PHP for my login script and mySQL for the database.

You could do this:
1. Process the login form (i.e. check password etc.);
2. If the user is logged in correctly and has the checkbox checked, you save
the username and a random string in your database;
3. You store the random string in the browser's cookie.

When the user comes back, you:
1. Check for a login cookie;
2. If there is such a cookie and you have the random string, you get the
username from the database and log in the user (with the PHP session).

You could also save the username and password in a cookie, but that is a bad
idea. The cookies, and thus the password, are saved as plain text on the
user's computer. That's not safe.

How should you implement this in PHP? An example:

the login script:
<?php
// after you checked the username and password,
// generate a random string
$key = md5(uniqid(microtime()));

// you then save username and key in the database
mysql_query('INSERT INTO keys SET key="'.$key.'", '.
            'username="'.$username'";');

// and save the key in a cookie
setcookie('remembercookie',    // the name of the cookie
          $key,                // the cookie value
          time()+60*60*24*30); // when the cookie will expire
                               // (= after 30 days)
?>

When the user comes back, you'll have to check for a 'remembercookie'. If he
has such a cookie, you log the user in as you would do after he filled in
your login form. You do this by including the following code in your
scripts:

<?php
// check for a 'remembercookie'
if (isset($_COOKIE['remembercookie'])) {
	// there is a cookie, lookup username
	$result = mysql_query('SELECT username FROM keys '.
                            'WHERE key="'.$key.'";');

	// is there such a key in the database?
	if (mysql_num_rows($result)==1) {
		$username = mysql_result($result, 0, 'username');
		// this user is logged in as $username
		...paste your session code...
	}
}
?>

HTH,

Gijs

--------------------------
Gijs van Tulder
gvtulder at members.evolt.org
http://gvtulder.f2o.org/




More information about the thelist mailing list