user3298214
user3298214

Reputation:

Setting sessions in cookies and retrieving the sessions from the cookie PHP

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.

Upvotes: 0

Views: 72

Answers (1)

AeroFufel
AeroFufel

Reputation: 51

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.

Upvotes: 1

Related Questions