Say database table's name for persistent cookie is pcookies with the following columns:
- cookie_id (CHAR)
- user_id (INT)
- expiry (DATETIME)
- salt (CHAR)
Cookie creation steps:
- After successful login, create a cookie record in database under an unique id. You may generate it by hash_hmac('sha512', $token, $salt) where $token=uniqid($user_id, TRUE) and $salt=md5(mt_rand()).
- Store 'user id', 'expiration time' and 'salt' along with the 'cookie id' in database.
- Store 'cookie id' and 'token' in cookie.
Authentication steps:
- If there is a persistent cookie found, first check whether the record is available in database or not.
- If the record is available then check whether the cookie expires or not.
- If the cookie does not expire, then validate the cookie id by $cookie_id == hash_hmac('sha512',$token_from_cookie,$salt_from_db).
- Once the cookie is validated, delete it from database and create a new cookie according to the above cookie creation steps.
- If the cookie is found as invalid, then clear the cookie from the device and delete all other cookie records of the user from database, notice the use about a theft attempt and proceed to manual login process.
Notes:
- When session is available, ignore checking cookie.
- After logout, clear the cookie along with the database record.
- Never allow users to execute sensitive requests like password change or view credit card information from a persistent cookie login. Invoke password to login and add a flag in the session to allow all onward operations.