How to do auto login, store the session in the bro

2019-04-03 01:57发布

问题:

I have seen some social network sites, if you have a user account, and when you open the browser and type the url, you will be directly loged in without inputting the username and password even if you close the computer and restart the browser your can still be automatically loged in which is different form before which you need to log in with your log in details, I think this is not only include the session cookie like the following

    setcookie(session_name(), '', time()-2592000, '/');

but might be more complicated than it. suppose if I use php, can anybody tell me how to implement this function, I assume it's done on the server side, sorry if I didn't make clear description.

回答1:

What I do is, I keep user ID and/or username and login hash, md5(userID + username + password) as cookies.

Upon another visit, take ID from cookie and check login hash against the same formula it was generated. If the same, login automatically.

Global

$randomSeperator = '!~!';

First Run...

$hash = md5($id . $randomSeperator . $username);
setCookie('id', $id);
setCookie('username', $username);
setCookie('hash', $hash);

Second Run...

$id/$username/$hash = $_COOKIE[][][] .... // Get all 3 cookies

if($hash == md5($id . $randomSeperator . $username) ){
// Do Autologin
}