PHP Session principle Analysis and use

Source: Internet
Author: User
Tags php session sha1 sha1 encryption ukey
Before a blog called The Magic Lab read a "PHP session principle of thorough analysis" of the article, the author from the point of view of the use of the session is very good in the code in the course of operation, the changes in each link and related parameters set and role. Originally wanted to reprint the original text, but the original blog was closed. I do not know whether this large-scale re-filing, or other reasons. Baidu snapshot to find some of the original information, not found will be in accordance with the previous understanding of the reorganization, so that we can have more understanding of the session.

Wedge: Session Plain English

Session, English translation for "conversation", two people chatting, from the first sentence to say hello, to the last sentence goodbye, this constitutes a session. The session in PHP mainly refers to the client browser and server-side data Exchange dialog, from the browser open to close, a simplest session cycle. How does computer language generally implement a conversation? To cite a popular example:
Service side like a barber shop, the client is like every barber to the guests, many barber shops have this promotion means, continuous consumption of 10 times guests, can be free once, about three ways to achieve:
1, Barber's memory is too good, you came a few times, he looked at a glance to know-this is called the agreement itself to support the session;
2, each guest issued a membership card, every time you spend, you have to take this card, the consumption of a record, of course, also stamped seal-this is called through the cookie to achieve the session, the disadvantage is not high security, I can counterfeit membership card or official seal;
3, the barber shop prepares a big book, the guest each corresponds to a member number or own personal data, even the password, each guest comes to consume, reports his own member number, then records the consumption number to the Big book-this is the session realizes the conversation, The guest in the mind of the membership number is stored in the client's SessionID, the Big book is saved on the server session data, so that compared to the second method, the security is much higher, unless you say that you have lost your membership number and password, this is called fake client SessionID.

Because the HTTP protocol is stateless, so PHP to implement the session only through the following two ways, the previous cookie, the shortcomings have been said, the security is not high, so important sessions will choose to use the session. Session sessions must rely on an identity, or can be understood as a code, that is, SessionID. This is an encrypted string, stored in the client, usually in the cookie, the client and the server each communication is through this SessionID, the client first tell, the servers can find you on the service side of the session data saved, continue to call.

PHP.ini Common session Settings

[Service side]
Session.save_handler = Files
The default is file, define the session on the server to save the way, file means to save Sesion to a temporary file, if we want to customize another way to save (such as with the database), you need to set the item to user;

Session.save_path = "/tmp/"
Defines the location of the temporary file where the server stores the session.

Session.auto_start = 0
In the case of 1, it is not necessary to write session_start () in each file; Session auto start.

session.gc_probability = 1
Session.gc_divisor = 100
Session.gc_maxlifetime = 1440
These three configuration combinations build a garbage collection mechanism for server session session.gc_probability and session.gc_divisor constitute the probability of performing session cleanup, The theoretical explanation is that the service side periodically has a certain probability to call the GC function to clean the session, the probability of cleanup is: Gc_probability/gc_divisor For example: 1/100 indicates that each new session is initialized, there is a 1% probability that the garbage collection program will start, The standard for cleanup is the time defined by Session.gc_maxlifetime.

Client
Session.use_cookies = 1
SessionID in the client-side storage method, 1 for the use of cookies to record the client's SessionID, while the $_cookie variable will have $_cookie[' Phpsessionid ') this element exists;

Session.use_only_cookies = 1
Also defines how the SessionID is stored on the client, and 1 means that only the cookie is used to hold the session ID. In general, the client now supports cookies, so it is recommended to set it to 1, which prevents attacks on passing the session ID through a URL.

Session.use_trans_sid = 0
Relative to the above setting, if set 1, the Representative allows sessionid through the URL parameter, the same, the proposed set to 0;

Session.referer_check =
This setting does not take effect until Session.use_trans_sid = 1, in order to check "Referer" in the HTTP header to determine if the session ID contained in the URL is valid, Http_referer must contain the string specified by this parameter. Otherwise, the session ID in the URL will be considered invalid. So the general default is null, that is, no check.

Session.name = Phpsessid
Defines the name of the SessionID, which is the variable name, which can be viewed by the browser HTTP tool phpsessid;

session.hash_function = 0
Choose Session_name Encryption method, 0 for MD5 encryption, 1 for SHA1 encryption, the default is 0, but it is said to use SHA1 encryption, higher security;

Session.hash_bits_per_character = 4
Specifies how many bit binary numbers are saved per word characters in the Session_name string, which is the result of the hash function's operation.
4 bits:0-9, A-f
5 bits:0-9, A-v
6 bits:0-9, A-Z, a-Z, "-", ","

Url_rewriter.tags = "a=href,area=href,frame=src,input=src,form=,fieldset="
Specifies which HTML tags are overridden to contain the SID (SESSION_ID) (valid only if "Session.use_trans_sid" is turned on), and the URL rewrite adds a hidden "<input>" It contains information that should have been appended to the URL.

Session.cookie_lifetime = 0
Save SessionID Cookie file life cycle, such as 0, on behalf of the end of the session, the SessionID will automatically disappear, the common force to close the browser, you will lose the last SessionID;

Session.cookie_path =/
Save the SessionID cookie file at the client's location;

Session.cookie_domain =/
Save the domain name setting of the SessionID cookie, which is related to the access permission setting of the domain name allowed by the cookie, in general want to let all the directories in your website have access to the client's cookie, should be set to "/" If you need more information, you can see the Setcookie () The domain parameter related setting and use method of the function;

session.bug_compat_42 = 1
Session.bug_compat_warn = 1
These two can be said almost obsolete settings, is for the old version of PHP services, mainly for the Session_register function, because the PHP5 register_global default is off state, so in PHP5 can not use Session_ Register this function, and PHP6 will abolish this setting, directly defined as close, so there is no need to study these two;


What did Session_Start () do?

Suppose that several key parameters of the session in PHP.ini are configured as:
Session.save_handler = Files
Session.use_cookies = 1
Session.name = Phpsessid
Session.save_path = "/tmp/"

The following code sample illustrates the role of Session_Start during a session.

Program 1:
<?php
Session_Start ();
$_session[' uname '] = ' monkey ';
$_session[' ukey '] = 20119999;
?>


After program 1 is executed, session_start () will do two things:


1, in the client to generate a PHPSESSID cookie file, the location and storage of this file is related to the way the program is executed, different browsers are not the same, this step will produce a serialized string--phpsessid To view the cookie information in the browser, you can install the relevant plugin. Httpfox,web developer in Firefox is a great tool.


2, on the server to generate a temporary file to hold the session data, the location of the storage is specified by the Session.save_path parameter, the name is similar to "sess_85891d6a81ab13965d349bde29b2306c", "Sess_" On behalf of this is a session file, "85891d6a81ab13965d349bde29b2306c" is the phpsessid of this conversation, and the client's PHPSESSID value is the same.
Using the editor to open the "sess_85891d6a81ab13965d349bde29b2306c" file, you will see a string of "Uname|s:6:" Monkey "; ukey|i:20119999;" Such a content. This file contains the specific contents of the $_session variable, each variable with ";" separated by semicolons.


Format: variable name | Variable type: [length]: value; For example: uname|s:6: "Monkey"; The type of the session variable uname is a string, the value length is 6, and the value is monkey.

So the question comes, and the two things mentioned above are done in the program execution to Session_Start ()? The two things, who first who after?
Let the experiment prove, slightly change the program:

Program 2:
<?php
Session_Start ();
$_session[' uname '] = ' monkey ';
$_session[' ukey '] = 20119999;

Sleep (30);
?>

First, the client and server session data are deleted, and then execute the program 2, while the program sleep30 seconds, to see the client and server session, found that: in the process of program execution, The client does not have a cookie file to save the PHPSESSID, the server has a temporary file to save the session content, but there is no content in the file, after 30 seconds, the client's cookie file will be generated. The content is only available in the session file on the server.


It is inferred that the approximate process should be: When the program executes to Session_Start (), the server first generates PHPSESSID, and generates the corresponding session file, but when the program is $_session assigned value, The corresponding value is not written to the session file, let's assume that it is stored in memory bar, until the completion of the program, will be generated in the client save Phpsessid cookie file, and the value of the $_session variable is written to the server session file, As for the last two steps who first who after, temporarily did not think of a good way to prove.


To further demonstrate, delete the client and server session-related content Execution Program 3, observe the results for the first and second times:
Program 3:
<?php
Session_Start ();
$_session[' uname '] = ' monkey ';
$session _id = session_id ();
$sess _file = "/tmp/sess_". $session _id;
$content = file_get_contents ($sess _file);

Echo ' * * * '. $_cookie[' phpsessid '. ' ***';
echo ' <br/> '. $_session[' uname '. ' <br/> ';
Echo ' * * * '. $content. ' ***';
?>


Above is the first time Sessin_start () execution, that is, a set of procedures, the first session_start () when the things that occur, the following look at the Session_Start ():

Hypothetical php.ini configuration: session.cookie_lifetime = 0

Program 4:
<?php
Session_Start ();
echo $_session[' uname '];
echo $_session[' Ukey '];
?>

Now, the client has saved Phpsessid cookie file, the server also has a Sess_ file to save the session content, execute program 4, will print the normal content. At this point, if you forcibly close the browser, and then execute program 4, what will be the result?

First, Session.cookie_lifetime is set to 0, indicating that the client saves Phpsessid cookie file life cycle is 0, if the browser is on, PHPSESSID value will be saved in memory, once forcibly closed, Save Phpsessid Cookie file will be destroyed at the same time, but the server does not perform Session_destroy (), so the server side of the session data file is still in, but when the browser opened the execution program 4, found nothing output, thus reasoning:


Session_Start () First to obtain the PHPSESSID in the client cookie, and then the "Sess_" to form a file name, go to the server to find the file, and then take out the contents of the file, put the content into the $_session global variables for use. The browser forcibly closed, and then opened, before the Phpsessid lost, then encountered Session_Start () is equivalent to the first execution, will generate a new PHPSESSID, this PHPSESSID matches the previous server's Sess_ file, So the content is not taken. Of course, the server also has a file that can match this phpsessid, but the file is still empty.


Therefore, some systems in order to achieve the same user can only be in one machine or even a browser login mechanism, if not modified session.cookie_lifetime settings, there will be forced to close the browser after the service side session lifetime before the deadline, User login does not go in the case, the better way is to set the Session.cookie_lifetime to a larger value, anyway, a cookie file exists for a long time some also have no effect.

  • 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.