开发者

Best way to allow authentication to a site from a cookie in PHP?

开发者 https://www.devze.com 2022-12-18 23:20 出处:网络
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

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开发者_如何学C
    }else{
        // redirect to login page
    }

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

}else{
    //user is logged in already
}


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
}


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号