Question

Is storing username & password of the user in a cookie a good practice? I really want to know how big websites like (Facebook, digg, twitter) handle this. My code is like that:

<?php

$username = mysql_real_escape_string($_POST['username']);
$password = md5($_POST['password']);

?>

After every successful login i store the $username and the $password (md5) in a cookie. And regenerate the session id with session_regenerate_id()


And to authenticate the user i check if a login session exists, otherwise i authenticate the cookies.

Any ideas? Thanks

Was it helpful?

Solution

I'm a bit confused – are you using PHP sessions, or cookies?

If you store the data in a session ($_SESSION['username'] = 'Tom' etc.), that data is not stored in the user cookie.

If you store the data in a separate cookie (for something like automatic login), you might want to store a different, random id instead, and look up the user id a database table.

autologins
----------
key (random hash)
user_id
expires

OTHER TIPS

Just an md5 is not enough, you should at least include a random 'salt' (a small random string of characters) that you store in your database.

Edit: Btw, did you store the password plain text or encrypted? That could be a bigger security risk.

The standard practice is to give the user a session ID in a cookie, either yourself or using PHP sessions. Storing the username and password hash in a cookie is still done by some sites, but I prefer the former. It allows you to give the users more control over their logins, so they can see how many sessions they have and which IP they are from, for example - see GMail for a good example.

On the subject of salts and hashing, you should store the password hashes in the database salted. Ideally the salt should be different for each user. In the event that your database is stolen or exposed, this will make it a LOT harder for an attacker to get passwords (if they all used the same salt they could generate rainbow tables for that salt, which takes a long time, but would let them then break passwords quite quickly). For security the salt should also contain some non alphanumeric characters, like %$&^.

Joel L's answer is a good one. The only thing I'd add is that instead of a random ID, you could add some extra information identifying the user to make it more secure.

For example, use a hash of the user's IP address and a salt, provides extra security against someone stealing or sniffing the user's security cookie.

I suspect that TWitter uses something like this, which is why you can only be permanently logged into Twitter from one computer at a time.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top