NardCake
NardCake

Reputation: 130

Implementing a "remember me" feature

Basically I have a login system with basic session functionality, and it times out on browser close. I've been getting complaints on that so I want to be able to have some click the remember tick and have their session last for say, 30 days.

Upvotes: 0

Views: 728

Answers (2)

NewInTheBusiness
NewInTheBusiness

Reputation: 1475

Set a cookie at the same time you're setting the $_SESSION['user_id'] for instance. Like this :

$token = hash('md5',$_SESSION['user_id'] . time() . 'salt');
setcookie('token', $token, time() + (3600 * 24 * 30));
setcookie('user_id', $_SESSION['user_id'], time() + (3600 * 24 * 30)); // Cookie expires in 30 days

Save $token in DB in user_id row.

Then you set the $_SESSION['user_id'] for users with cookies saved so they don't have to sign in the normal way:

if (!isset($_SESSION['user_id']) {

    if (isset($_COOKIE['user_id']) && isset($_COOKIE['token']) {

       $saved_token = SELECT token FROM users table WHERE userID = $_COOKIE['user_id'];
         if ($_COOKIE['token'] == $saved_token) { 
         $_SESSION['user_id'] = $_COOKIE['user_id'];
       } else log out
       }
}  else log out
}
}

Maybe that works better security wise?

Upvotes: -1

Shubham
Shubham

Reputation: 22307

As said this can be done with cookies. There are plenty of tutorials but a good approach is necessary for security. I still remember, in Orkut, the long dead social networking site, you could just ask the user to run some script steal his cookies and viola the account is yours even if the user had logged out.

So here is a the best approach.

  • Create a cookie on user, hashing the user id with some salt, call it user token.

  • In your database store the token with user it belongs to and its expiry date.

  • Now when user visits with his cookie, just check if the hash is there in database and log the visitor in.

  • When user logs out just delete that token from database.

(More information)

Upvotes: 2

Related Questions