good day..I have a problem, but I think it's not really a problem. I'm just curios about the php cookie. I have set it up on my website. I use it as a basis for "remember me" checkbox and it's working properly,but, I don't really what are the importance of setting up a cookie. Will I use it to automatically logged in a user which does not press the logout button but maybe just close the browser? or can I use it just to save thier email address and let them fill-up the password field? It really bothers me. What is really the importance of cookie. What I mean is, how do I use the cookie properly? I hope you understand my question. Please help me clear this cookie thing. Really appreciate if you would answer this. Thanks. don't be harsh on me :-)
Cookies are a user-controllable variables. Just like $_GET. So, before using it, for example, as a path parameter in accessing files, take care that it's value is really what it should be.
Setting setcookie() optional parameters can prevent a lot of attacks too. Documentation is here: http://php.net/setcookie
When you call setcookie(), it sends a soft request to browser to set cookie amongst other responses, so it is up to browser to support cookies or not. Only save public and not important data in cookies. By saving password in cookies, a man-in-the-middle attack will reveals password. Also by accessing to client's hardware fore a few minutes, kids can reveal passwords too. So, what you need is storing a long really-random login key + row id of signin table in database, where it has columns such as row-id, random-login-key, user-id, signin-time, last-visit time, etc.
A 256 bit (32 bytes) or 512 bit (64 bytes) random value for login key is enough.
mt_rand() and rand() are not secure random generators, so use one of following functions to generate a secure random bytes:
http://php.net/openssl_random_pseudo_bytes
http://php.net/mcrypt_create_iv
# License: wtfpl - http://www.wtfpl.net/txt/copying/
function random_bytes($size)
{
if(function_exists('openssl_random_pseudo_bytes'))
{
$bytes = openssl_random_pseudo_bytes($size, $is_strong);
if($is_strong === true)
return $bytes;
}
if(function_exists('mcrypt_create_iv'))
return mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
else
{
$bytes = '';
for($i=0; $i < $size; $i++)
$bytes .= chr(mt_rand(0, 255));
return $bytes;
}
}
Even though it's not totally secure to save login key to cookies, but it is the only way that all websites do it. For a total security, use HTTPS protocol.
Also, you may want to check out Authentication, Session Management and cookie theft/session hijacking cheat sheets at owasp.org.