Your approach is very suitable for regular sessions. The problem bit here is the Remember Me function, which needs to be handled differently than a regular session.
A common way to implement this feature is to save a second cookie with an expiration date and add a user ID and a secure hash. You need a user ID or other identification to determine which user is returning, but you also need a secure hash to ensure that the cookie is the one set by your web application and has not been manually created. If you donβt have a secure hash, people can send a built-in cookie with a user ID and log in automatically.
Thus, a secure hash should contain information that only your web application knows about, that is, the date the user was created.
You might want to do this as follows:
$cookieValue = (int)$user->id . ':' . md5($user->creationDate . '/' . $user->passwordHash);
Since neither creationDate nor passwordHash changes, you can verify the validity of the secure hash when a user tries to log in through a cookie. When the user changed his password, the password hash changes, and the user needs a new cookie, which is very good in my eyes, since the people who stole the cookie also logged out.
If you need extra security , use a different value to create a hash, that is, a special hash cookie that you store along with other user data. You can create it completely randomly and change it every time a user logs in:
$randomValue = md5(time() . rand() . $user->passwordHash); $user->setCookieValue($randomValue); $cookieValue = (int)$user->id . ':' . $randomValue;
Now at login:
list($userId, $hash) = explode(':', $cookieValue); $user = loadUser($userId); if ($user instanceof User && $user->cookieValue == $hash) {