views:

69

answers:

3

I know this is a basic question so it should be a basic answer. I have always done a user login system using sessions only, I would like to now make it an option for a user to stay logged in when they come back to my site if they choose to by using cookies. I am not sure the best way of doing this but I have a small mockup of the basic functionality the way I think it might work below. Please tell me if that looks about right or if I should be doing it differently. The cookie will most likely hold a user ID and some encrypted key that would be re-generated everytime they "login"

// see if Session is set
if (!isset($_SESSION['userID']) || $_SESSION['userID'] == ''){

    // session is not set so see if cookie is set
    if (isset($_COOKIE['userID'])){
        //cookie is set so check that it is valid login ID and key
        // if it returns tru then we will also initiate there session value so they will be logged in
    }else{
        // redirect to login page
    }

    if (!isset($_SESSION['userID']) || $_SESSION['userID'] == ''){
        // redirect to login page
    }

}else{
    //user is logged in already
}
A: 

You're on the right track; this is how most "remember me" implementations work.

Johannes Gorset
A: 

You do it the same way sessions work, except have the session cookie last longer than the life of the browser session.

Tim Cooper
+1  A: 

What I have used in the past is setting two cookies, one storing the userid and one containing a checksum that validates the userid. Here is an example:

//store website user id
setcookie('userid', $userid, time() + 2592000, "/");
//store checksum
setcookie('checksum', md5($userid."F%^WD&*^("), time() + 2592000, "/");

The checksum is a salted md5-hash of the userid, so it cannot be reverse engineered or altered to reflect another userid (in case of no checksum, one could easily change the 'userid' cookie).

To restore the session, you just check for the cookies and validate the checksum (with the same 'salt') against the userid:

//Restore stored user session
if (md5($_COOKIE["userid"]."F%^WD&*^(") == $_COOKIE["checksum"])
{
    //retrieve user again and store in session
}
Arjan