What is the function of keeping the login status in the PHP website?

Source: Internet
Author: User
Keywords Cookies
Tags php website set cookie setcookie
Most Web sites provide a "Remember Me" or "Stay signed in" option when a user logs in, and I only know it is done with cookies, but what is the specific workflow? Because you want to implement a website login, so you want to understand the details of the problem.

Reply content:

I'm going to talk about the problem.
First of all, based on the above mentioned by several friends, session information stored on the server side, relative to the cookie stored on the client is more secure, so normal general web site in the "Determine whether the user is logged on", it is true to use the session, for example, you can store the following array in the session
//验证用户名和密码成功后$_SESSION['userinfo'] = [  'uid' => 123,  'username' => 'testuser'];
There are cookie-related functions in PHP, and when the user logs in successfully, the following statements are possible:
Setcookie ("User", "user1", Time () +3600);

To determine if a user is logged in, there is a statement like this:
if (Isset ($_cookie["user")) {
echo "already logged in";
}

When the user exits, there is a statement like this:
Setcookie ("User", "", Time ()-3600);

If the user has not clicked the Exit button after logging in, the cookie will expire after 3,600 seconds.
If you want to keep the user long enough time () +3600*24*365 is valid for one year after logging in. Look at the specific needs, if it is local to remember that the direct use of cookies, the user name and other information stored up, this is enough. If it is free to log in anywhere for a period of time, the server is present with the session. Then, when you visit the site, you directly determine whether a cookie or session has valid login information. Of course, for security, you can encrypt the user information and store it after encryption. As mentioned earlier, using the user name as the session ID, it is a bad practice to save the data from the session to the database check every time.
The first method completely avoids the construction request to obtain the user data, also does not have the flexible use session, does not have the login to have the session data?
The second procedure completely misuse the role of the session, if you take the session to save the user account to go to the database to fetch data, the session to save the user account is completely meaningless.
Also exiting the browser does not automatically delete the Web site cookie data, and the validity period of the cookie is determined based on the timeout value of the set cookie, and the time-out is not cleared.

1, SessionID is how to generate, after receiving the request, it is necessary to determine whether the cookie commits the SessionID parameter, does not exist to generate an identity through the set cookie notification browser record SessionID. At the same time, this sessionid is the server that identifies the data required to store the browser session state.
This operation has nothing to do with login. This action can be set for any request. Used to identify the session state between the browser and the server.

2, how to realize the logging user login status, usually after the login check in the cookie expiration time on the work, rather than the user name password stored in any form on the client or client. For example, in the case of 1 steps, the set cookie notifies the browser that the cookie expires for one months, while the server's cache record is logged in and the expiration time is set to one months.

This way, as long as the browser does not clean the cookie, each request server parameter will automatically put the cookie stored in the SessionID to the server, so that the server can be Get_session_info (SessionID) to obtain the session state of sensitive data, such as login status, user name and other data. This allows you to save the login state.

3, do not recommend things to do
It is not recommended to do any recording of user's personal information in front of the browser, save a logo.
It is not recommended to do any read database operation when the session data is fetched, the purpose of the session is to cache the data required by the browser session and avoid reading the database.
It is not recommended to use a single sessionid as the identification, like the left bank answer, use at least one random string as the check mark, avoid SessionID collision. Everyone prawns good, I just say my own understanding ....

If you only use cookies, it seems that you can also implement the login function, but usually use the session to achieve login it?

After session_start in PHP will produce a session file, usually placed in the TMP directory, but also set a client's cookie, and the value of this cookie is actually randomly generated session ID, so that a session has been established

In this way, each time the HTTP request is sent, the server associates the cookie with the session ID and the file content of that session, and the PHP program can also get the session information through the Super global variable $_session.

But so far, is only a session of the establishment, not a user login, the general sense of login should refer to the current user's information and this session association, in PHP is generally, first through user-submitted user name and password to verify, the derived information to $_session assignment

I think this is the process of a login, probably tidy up a bit is:

1.session Start Build session
2. Verify the user name password sent by the user, and verify that the user information is associated with the session

The establishment of a session lets the server always know that these requests are the same user, and the user is logged in to let the server know which user this has been

The reason for this is because HTTP itself is a stateless protocol, so the application itself is going to save some information at both ends for state confirmation

You prawns, I have been so to achieve the login, I do not know if there is any problem, if there is a problem, the heroes must point out Ah, especially the security aspects of

This will save me from making more serious mistakes. Cookies are stored in the client, there is the risk of being arbitrarily tampered with, so in fact the server to determine the user login status, is generally used session ... Session data is stored in the server, but the client's cookie must be found to the corresponding session
so the process of user login is actually
1: User input user name password, post data to server
2: The server determines whether the user name password is correct, if correct, the client creates a store session_id cookie, and in the server to create a corresponding session_id session,session inside the data may be the user's data
3: The user after the operation, first remove the session_id from the client, find the corresponding session of the server, take out the data, check and then proceed to the next step.
and say what I understand, stay on the log.
since cookies are stored on the client, it is not recommended to use Isset ($_cookie[' username ') to determine whether the user is logged on.
Because the user can completely forge a cookie, to achieve the purpose of spoofing the server ...
So, the two ways I think of it are:
1: Above someone said, store username and encrypted password, once again access, the server takes out cookie data, with the database to do proofreading, if passed, then judged to have landed
2: Build a MySQL table, which is stored cookie_id,username,expire,time, and then each time you log in, according to the user choose to save the login time, to generate a MD5 encrypted cookie_id (can be generated with username, timestamp and random numbers ), and then insert the Cookie_id,username, the user keeps the login time, the current time stamp together into the database, and create a cookie named Cookieid, which is the MD5 encrypted cookie_id above.
Then the next time the user accesses, the server can first take the cookie, according to the cookie Cookieid find the corresponding database data, to determine whether there is no legal cookie, there is no life cycle, etc... If all passes can be judged as landing ...
Above purely for personal opinion, if there is inappropriate, please advise first to say the conclusion:
Both 1.cookie and session can be used to keep the login status.
2. If a cookie is used, the cookie used to hold the user's state needs to be encrypted and identifiable, but it must not be decrypted. This means that the encryption of the user login information stored in the cookie data on the server can be restored, even if not restore can also be used to identify and compare (that is, the only), PHP encryption function can go online search, a lot of search.
3. If the session is used, it is easy to use $_session as a global array without regard to security, but if higher security is required, additional parameters are required for security validation, either as an encrypted string or as a MD5 fingerprint of a string of data.
4. Using the session can guarantee the consistency of the login data, if there are items in the login data that may change during the login time, but still need to use additional parameters to extract the original session data.
5.cookie is a lag from the session, which needs to be noted, sometimes beneficial, and sometimes inconvenient.
6. After fully understanding the working mechanism of the session, we can try to discard the session mechanism of PHP itself and establish a custom session mechanism.

The ultimate conclusion:
In order to ensure security, since the need to encrypt cookies, then, why not the user login data stored in the cookie? Session also wastes server-side storage.

Ultimate Advanced Conclusion:
When you learn to use an in-memory database, such as memcached or Redis, cookies and their combination are the perfect solution.

Here's something else:

Speaking of the state to maintain this thing, has been the sore of HTTP, because HTTP is a stateless protocol, to let stateless protocol support state maintenance, so the creation of a cookie, the early browser on the cookie is very large, so reluctant to use the Get parameter is also the right thing, Modern browsers open cookies by default, and most of them already support browser-side storage (storage) and a small portion of the browser-side database, both of which are stored, and do not feed back data to the server when requested. The session is based on cookies or other data returned from the browser, separated from the cookie or other parameters from the browser (such as Get parameters) is water without, no root wood.
It has been said that even a lot of people say that the session is safer than a cookie, which I think is an inappropriate view. Cookies and sessions are equally secure and do not store cookies on the server because they are stored on the client side and make the cookie less secure than the session, so to speak, The security of the cookie and session is determined by the security of the cookie or the parameters referred to in the previous article to return the server.
And the session is not only limited to the session library provided by PHP itself, any data stored on the server side may play the role of the session, in essence, the session is a special kind of database, but this database only allows the only identified legitimate clients to access.
Although I emphasized the only one in the above paragraph, the identification process is unreliable, that is, it may not be unique, which is called the source of insecurity. In fact, since the advent of the Internet, it has been rife with deception and violence. Nothing in this world is unique, just as nothing is exactly the same, although philosophy has taught us that there are not two identical things in the world, and no two completely independent things, but this absolute concept is not suitable for relative life. Life, there is only this concept, but unfortunately there is no single fact. Even if there is a pillow person warm words whisper to tell you, you are his only, if you really believe, it can only be you too naïve. The only thing that matters is that there is a difference between the granularity, in the recognizable range, the only meaningful, but this meaningful but really heartbreaking, recognizable means to judge whether a thing is the only rule is limited, the limited means that can be counterfeit, today, mankind has created a variety of technologies used to identify uniqueness, But the recognition technology is still developing and never-ending.

Finally, a few cookie manipulation functions are included:
Feature 1: The delay of the cookie is removed, i.e. it is ready to use.
Feature 2: It is convenient to store an array in a cookie without the need for a write Setcookie statement.
Feature 3: Support "." indexes, such as TEST.AAAA.BBBB, refer to the TEST[AAAA][BBBB in a cookie].
Note 1: Be careful with the 4kb limitation of cookies, although some modern browsers may extend this limitation.
Note that there are too many things in 2:cookie. After all, increased network data transmission and server processing.

function Set_cookie ($data, $path = '/', $time = 0, $doma = NULL){if (!is_array ($data)){$para = Func_get_args ();$data = Array ($para [0] = = $para [1]);$path = Isset ($para [2])? $para [2]: '/';$time = Isset ($para [3])? $para [3]: 0;$doma = Isset ($para [4])? $para [4]: NULL;}if (Is_int ($path)){$time = $path;$path = '/';}if (is_string ($time)){$doma = $time;$time = 0;}$time = $time = = = 0? $time: Time () + $time;foreach ($data as $key = $value){if (!is_array ($value)){if (Strpos ($key, '. ') = = = = FALSE){if (isset ($_cookie[$key])){if (Is_array ($_cookie[$key])){$cookie _str = http_build_query (Array ($key = $_cookie[$key]);$cookie _arr = Explode (' & ', $cookie _str);foreach ($cookie _arr as $cookie){$a _cookie = explode (' = ', $cookie);Setcookie (UrlDecode ($a _cookie[0]), Null,-1, $path, $doma);}$_cookie[$key] = NULL;}}Setcookie ($key, $value, $time, $path, $doma);$_cookie[$key] = $value;}Else{$cop = &$_COOKIE;$cox = Substr_count ($key, '. ');foreach (Explode ('. ', $key) as $ckk = + $ckey){if ($ckk > 0){$cookie _key. = ' ['. $ckey. '] ';}Else{$cookie _key = $ckey;}if ($ckk < $cox){if (isset ($cop [$ckey])){if (!is_array ($cop [$ckey])){Setcookie ($cookie _key,null,-1, $path, $doma);$cop [$ckey] = NULL;}}Else{$cop [$ckey] = NULL;}$cop = & $cop [$ckey];}Else{if (isset ($cop [$ckey])){if (Is_array ($cop [$ckey])){$cookie _str = http_build_query (Array ($cookie _key = $cop [$ckey]));$cookie _arr = Explode (' & ', $cookie _str);foreach ($cookie _arr as $cookie){$a _cookie = explode (' = ', $cookie);Setcookie (UrlDecode ($a _cookie[0]), Null,-1, $path, $doma);}$cop [$ckey] = NULL;}}Else{$cop [$ckey] = NULL;}$cop = & $cop [$ckey];}}Setcookie ($cookie _key, $value, $time, $path, $doma);$cop = $value;}}Else{$x _cookie_str = Http_build_query ($value);$x _cookie_arr = Explode (' & ', $x _cookie_str);foreach ($x _cookie_arr as $x _cookie){$a _cookie = explode (' = ', $x _cookie);if (isset ($a _cookie[1) ){Set_cookie ($key. '. Str_replace (Array (' [', '] '), Array ('. ', '), UrlDecode ($a _cookie[0]), UrlDecode ($a _cookie[1]), $time, $path, $doma);}}}}}function Cookie ($key = NULL, $def = FALSE){if (!empty ($key)){if (Strpos ($key, '. ') = = = = FALSE){if (isset ($_cookie[$key])){return $_cookie[$key];}Else{return $def;}}Else{$cop = &$_COOKIE;foreach (Explode ('. ', $key) as $ckey){if (isset ($cop [$ckey])){$cop = & $cop [$ckey];}Else{return $def;}}return $COP;}}Else{return $_cookie;}}function Unset_cookie ($key = null, $path = '/', $doma = null){if (!empty ($key)){if (Strpos ($key, '. ') = = = = FALSE){if (isset ($_cookie[$key])){if (!is_array ($_cookie[$key])){Setcookie ($key, Null,-1, $path, $doma);}Else{$cookie _str = http_build_query (Array ($key = $_cookie[$key]);$cookie _arr = Explode (' & ', $cookie _str);foreach ($cookie _arr as $cookie){$a _cookie = explode (' = ', $cookie);Setcookie (UrlDecode ($a _cookie[0]), Null,-1, $path, $doma);}}unset ($_cookie[$key]);}}Else{$cop = &$_COOKIE;$ckeys = Explode ('. ', $key);$pop _ckey = Array_pop ($ckeys);foreach ($ckeys as $ckk = $ckey){if ($ckk > 0){$cookie _key. = ' ['. $ckey. '] ';}Else{$cookie _key = $ckey;}if (isset ($cop [$ckey])){$cop = & $cop [$ckey];}Else{return;}}if (isset ($cop [$pop _ckey] ){if (!is_array ($cop [$pop _ckey] ){Setcookie ($cookie _key. ' ['. $pop _ckey] ', null,-1, $path, $doma);}Else{$cookie _str = http_build_query (Array ($cookie _key. ' ['. $pop _ckey. '] ' = $cop [$pop _ckey]);$cookie _arr = Explode (' & ', $cookie _str);foreach ($cookie _arr as $cookie){$a _cookie = explode (' = ', $cookie);Setcookie (UrlDecode ($a _cookie[0]), Null,-1, $path, $doma);}}unset ($cop [$pop _ckey]);}}}Else{if (!empty ($_cookie)){$cookie _str = Http_build_query ($_cookie);$cookie _arr = Explode (' & ', $cookie _str);foreach ($cookie _arr as $cookie){$a _cookie = explode (' = ', $cookie);Setcookie (UrlDecode ($a _cookie[0]), Null,-1, $path, $doma);}$_cookie = Array ();}}}
Although both the cookie and the session can implement the function that the main owner wants, it is more recommended to use the session.
The reason is none of him, only because more secure, not easily intercepted forged login information.
// 登录成功后记录登录信息$_SESSION['loginStatus'] = array(    'username' => $username,    'status' => true,    'loginTime' = > time(),);...// 判断session信息if(empty($_SESSION['loginStatus']['status']) || !$_SESSION['loginStatus']['status']) {    // 引导到登录页} else {    // 加载用户信息}
Cookie and Session I remember the Hanshunping teacher's video, which has a tutorial dedicated to writing login modules.
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.