PHP login session and cookie
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 :)
}
UPDATE:
I wrote this article that covers this concept. Hope it helps.
You should be storing the random session value in the cookie. You definitely should not be storing any information about the user in the cookie itself. You can then check the session id in the cookie on each page load to ensure that (a) the user should have access to that content and (b) that the session ID is valid.
In PHP you can use session_set_cookie_params
and session_name
to set the parameters of the cookie.
For who may prefer using cookies (So you can access it long time later even if the browser was closed) this is a safe way to store even rough ID in cookies:
- Create a new field in users database name it X.
- Generate a cookie to keep the user ID.
- Generate a safe (say long) RandomString and keep it in another cookie.
- Also save that random string in the filed of X.
- In members area check if cookies of ID and RandomString match the database information.
- Clear column X when user signs out and generate data for X on next login.
To prevent library attack to match that random string, you may also force logout as soon as the check fails or blocking that IP for a certain time.