Currently, after a user logs in, I simply store the user’s ID number in a cookie using the following PHP code:
setcookie('userid', "$userid", time()+60*60*24*7*2, '/');
The above code sets a cookie that lasts for 2 weeks and contains the user’s ID number (stored in the variable $userid) that is not private. It also allows the user to stay logged in for 2 weeks. I am aware that this is probably one of the least secure ways to set a cookie to indicate that a user is logged in, since one can simply change his or her cookie parameter and log in as any user he or she wishes.
Therefore, how do a I set a cookie that accomplishes everything my cookie above accomplishes but is also secure?
In other words, what is the best way for me set a cookie that is secure and allows me at the very least to identify the user’s ID number during his or her session? I would also like the cookie to last 2 weeks, so the user doesn’t have to keep logging back into my website.
Use sessions instead. It’ll store a session ID in a cookie but all the actual data is stored on the server so nobody can mess with it.