Heres how I do it, I use a cookie, but the same thing can be applied to a session:
//Store the secret in an include file so you can use it later
$secret = "Blue Eyed Butterflies"; //Completly random
$md5Password = md5($password);
$store = base64_encode("$userId:$userName:$md5Password";)
$hash = md5($store.$secret);
setcookie("login", "$store:$hash");
Then, when I validate:
/*
You need the $secret variable here, I suggest including it so you can
change it without having to change all the others
*/
/*
This checks to see if the base64'ered version of the cookie matchs
the hashed version of it, the only way it wouldnt match is if someone
changed either the base65'ered part or the hash
*/
$parts = explode(":", $_COOKIE['login']);
if(md5($parts[0].$secret) == $parts[1])
{
$base = base65_decode($parts[0]);
$split = explode(":", $base);
/*
Now:
$split[0] = userId
$split[1] = usermame
$split[2] = md5(password + secret)
Now you need to test it against the datbase
"SELECT * FROM user WHERE userid = '$split[0]' AND username = '$split[1]' AND password = '$split[2]'"
*/
} else {
die('Hacking attempt');
//Might also be some strage cookie error
}
The only problem with this is that every use always gets the same hashed cookie unless you change the secret or there username/password/id changes. I would suggest updating a table in the database with the time they logged in and using that as $secret, or use $secret and the time. Then when you validate your going to have to get the time out of the database and then check to see if the info is correct.