php user autologin
Can't find answer to my question. I'm creating registrat开发者_Go百科ion and need autologin for user with cookie. What kind of information should be stored in cookie? Is it username + hash password or what
First, just to echo what everyone else has said, this isn't so much an auto-login feature as it is a 'remember me if I navigate away from the page' feature.
How I have seen it done in the past is similar to the implementation explained by frostymarvelous. Basically I have seen 3 cookies used:
Cookie 1:
- name - 'username'
- value - user's name
Cookie 2:
- name - 'salt'
- value - random salt created for this particular login
Cookie 3:
- name - 'authentication_hash'
- value - Hash of a couple unique pieces of data that only your website can duplicate. If you can duplicate this value in the cookie, then make sure the user doesn't have to login again.
Basically, cookie 3 is the most important cookie and I would include a couple things in this to prevent it from being duplicated easily:
<?php
function isAuthenticationCookieValid() {
// $websitePassword would be a unique string stored in a file that is only
// accessible by the server running your website.
include("websitePassword.php");
// $hashOfUserPassword should be a hash of the user's password and should be
// retrieved from the database in hashed form because that is how you should
// store passwords.
$hashOfUserPassword = retrieveUserPasswordFromDatabase($_COOKIE['username']);
// $salt should just be read from cookie.
$salt = $_COOKIE['salt'];
$authenticationValue = sha1($websitePassword . $salt . $hashOfUserPassword);
// Compare authentication value in cookie with calculated authentication value.
return $authenticationValue == $_COOKIE['authentication_hash'];
}
?>
The contents of 'websitePassword.php' should just be:
<?php
$websitePassword = "secretWebsitePassword"; // Obviously use a better password
?>
I would also suggest making the cookies expire after a timelimit to make your website more secure and you could possibly add a time element to your hash so if they try to use that particular hash after a particular amount of time, they will not be logged in automatically.
I would not store the hash of the password in a cookie because the hashing can be reversed (at least for weaker passwords).
Generate a session token which you can store in your database and use in cookies.
See: Session token - how does it work?
What I do is, I hash the useragent, tack the user ID the end of the string. When a user is not logged in, I check for the cookie, split the string, verify that the useragent is the same, and then proceed to log the user ID in. This btw is not too secure, but it is basically the way It is done. This is remember me btw.
For an auto login like xtgem, an url with the username and unique identifier is given to you. This is bookmarked and when the user clicks it, the page makes the checks and logs users in.
精彩评论