0

Is it possible to set a cookie with the session that has been created and with the session ID and then retrieve the session from the cookie next time you visit the page. I am trying to make a remember me button on my login page and wondered if this could be done this way.

  • A remember me checkbox usually refers to the time the server will wait before invalidating your session. You can simply check if it's checked and give them a longer time. A [related question](http://stackoverflow.com/questions/520237/how-do-i-expire-a-php-session-after-30-minutes?rq=1) shows how can expire a session after 30 minutes. Look at the conclusion/best solution. You can save a value within their session to see if they checked remember me or not. Based on their choice, you can decide to remove their session in 30 minutes or 5 hours. – Dave Chen Jul 06 '14 at 19:27
  • @DaveChen Thank you for your answer, I have come across `ini_set('session.gc_maxlifetime', '31536000');` which I believe should keep the session open for a year. –  Jul 06 '14 at 19:37
  • If I haven't misunderstood your question: being that you would like session expiry to vary between users who have checked remember me and users who have left it unchecked. That setting will change all sessions, don't you want to change the session life based on the user's choices? In that case I would like to point you in the direction of `if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1800)) {` which was listed under the `Conclusion` of the first answer. – Dave Chen Jul 06 '14 at 19:41

1 Answers1

1

Do not try to prolong a PHP session in order to build "Remember Me" feature. It's much better to re-initialize the session.

The most common scenario is this:

  1. When a user comes to a website with checked "Remember Me" checkbox, the website generates a unique code (a pretty long random string) and stores it in the cookies and a server side database.

  2. When the user closes a browser the session closes, but cookie stays.

  3. The next time the user comes the server will see the cookie, find it in the database and authenticate him based on the code instead of user/password pair.

This would be a good starting point, but in addition there are several enhancements are possible:

  1. You could save a username in the cookie along with the unique code. It's safer and faster to authenticate using this pair.

  2. You could save a user's IP in the database, so that authenticating data will work from this IP only.

  3. Instead of generating the unique code and saving it to the database, you could build the code on the fly as a hash based on user password plus salt. This saves your database from write operations.

Based on security/speed requirements there could be variations of this scenario, but the base stays the same: mark a user using cookie, re-authenticate him once he comes back.

AeroFufel
  • 51
  • 3