Adam Strudwick Adam Strudwick - 4 months ago 19
PHP Question

PHP login session and cookie

On my PHP website, users can login and have the possibility to check "Remember me" to set a cookie.

What should I be storing as a

variable? The username, hashed password and
user ID
, or only the
user ID
? If I only store the
user ID
, wouldn't it be possible for someone to edit the
and change the ID?

What about the
? Should I store only the
user ID
? As far as I know, cookies can be modified by the end user...


It seems that you don't have a clear vision of sessions and cookies!

No body can change the session contents except your code (beside attacks). So you can store everything (reasonable) like user id or username that you need to access frequently. in cookies you must store some obfuscated information that you can recognize user later when he/she tries to access your page. so based on cookie content you can regenerate users session (ie. re-login user automatically). Just to note that user CAN change cookies content so it must not be something simple like user id for security reason.

I just give you a simple example, it's far from perfect but not so bad! you may need to tailor it to fit your scenario:

here you can create cookie content like this:

$salt = substr (md5($password), 0, 2);
$cookie = base64_encode ("$username:" . md5 ($password, $salt));
setcookie ('my-secret-cookie', $cookie);

// and later to re-login user you do:
$cookie = $_COOKIE['my-secret-cookie'];
$content = base64_decode ($cookie);
list($username, $hashed_password) = explode (':', $hash);

// here you need to fetch real password from database based on username. ($password)
if (md5($password, substr(md5($password), 0, 2)) == $hashed_password) {
    // you can consider use as logged in
    // do whatever you want :)


I wrote this article that covers this concept. Hope it helps.