PHPSession principle analysis and application

Source: Internet
Author: User
Tags sha1 encryption ukey
PHPSession principle analysis and usage ???? I have read an article titled "thorough analysis of phpsession principles" in a blog called Magic Lab. from the perspective of session usage, I have elaborated on the code running process, changes in each link and settings and functions of relevant parameters. I wanted to post the original article, but the original blog was closed. I do not know how PHP Session works

???? I have read an article titled thorough analysis of php session principles in a blog called Magic Lab. from the perspective of session usage, I have elaborated on the code running process, changes in each link and settings and functions of relevant parameters. I wanted to post the original article, but the original blog was closed. I don't know if it is because of this large-scale record filing or other reasons. You can use Baidu snapshots to find some original documents. if you cannot find the original documents, you can reorganize them based on your previous understanding so that you can learn more about the session.

Wedge: Session vernacular

Session. two people chat, from the first sentence to the last sentence goodbye, this constitutes a Session. The session in PHP mainly refers to the conversation between the client browser and the server, which is the simplest session cycle from opening to closing the browser. How do computer languages implement sessions? For example:
The server is like a barber shop. the client is like a guest who goes to a haircut. many barber shops use this promotion method. customers who consume for 10 consecutive times can enjoy one free time. There are three methods to achieve this:
1. the Barber master has a good memory. after several visits, he will know at a glance-the protocol itself supports sessions;
2. each guest sends a membership card. each time you consume the card, you need to make a purchase record and stamp it with a seal. this is called session through cookies, the disadvantage is that the security is not high. I can forge a membership card or an official seal;
3. prepare a large account book for the barber shop. each guest corresponds to a member number, his/her personal data, and even a password. each guest will consume the account and report his/her membership number, then, record the consumption count to the large account book-this is the session Implementation session. the member number in the guest's mind is the SESSIONID stored on the client, and the large account is the session data stored on the server, in this way, the security is much higher than the second method, unless you say that you have lost both your membership number and password, which is called forging the SESSIONID of the client.
?
Because the http protocol is stateless, php can only implement the session in the following two ways: the previous cookie. the disadvantage has been mentioned, and the security is not high, therefore, important sessions use sessions. A session must depend on one identifier. It can also be understood as a hidden number, that is, SESSIONID. This is an encrypted string stored on the client. generally, in cookies, the client and the server communicate with each other through this SESSIONID, the server can find the session data you saved on the server and continue the call.

Php. ini common session settings

[Server]
Session. save_handler = files
The default value is file, which defines the session storage method on the server. file means to save the sesion to a temporary file. if we want to save the session in another way (such as using a database ), you need to set this item to user;
?
Session. save_path = "/tmp /"
Defines the location of the temporary file on which the server stores the session.
?
Session. auto_start = 0
If this parameter is set to 1, you do not need to write session_start (); session automatic start in each file.
?
Session. gc_probability = 1
Session. gc_divisor = 100
Session. gc_maxlife time = 1440
These three configurations are combined to construct the server session garbage collection mechanism session. gc_probability and session. gc_divisor constitutes the probability of executing session cleanup. Theoretically, the server regularly has a certain probability to call the gc function to clear the session. the probability of cleaning is: gc_probability/gc_divisor for example: 1/100? Indicates that each new session is initialized with a 1% probability that the garbage collection program will be started. the cleanup standard is the time defined by session. gc_maxlifetime.
?
[Client]
Session. use_cookies = 1
Sessionid is stored on the client. if set to 1, the sessionid of the client is recorded using the cookie. at the same time, $ _ COOKIE ['phpsessionid'] exists in the $ _ COOKIE variable;
?
Session. use_only_cookies = 1
It also defines the storage method used by sessionid on the client. Setting 1 indicates that session IDs are only stored using cookies. Generally, the client now supports cookies, so we recommend setting it to 1 to prevent attacks related to passing session IDs through URLs.
?
Session. use_trans_sid = 0
The parameter corresponds to the preceding setting. If this parameter is set to 1, sessionid is allowed to be passed through the url parameter. Similarly, it is recommended to set it to 0;
?
Session. referer_check =?
This setting is in session. use_trans_sid = 1 will take effect, the purpose is to check the "Referer" in the HTTP header to determine whether 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 is considered invalid. So the default value is null, that is, do not check .?
?
Session. name = PHPSESSID
Define the name of sessionid, that is, the variable name. you can view the PHPSESSID value through the http tool of the browser;
?
Session. hash_function = 0
Select the encryption method of session_name. 0 indicates md5 encryption, and 1 indicates sha1 encryption. the default value is 0. However, it is said that sha1 encryption is used to ensure higher security;
?
Session. hash_bits_per_character = 4
Specify the number of bits saved in each character in the session_name string. These bits are the calculation results of the hash function.
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 to override to include sid (session_id) (only valid when "session. use_trans_sid" is enabled). The URL writer adds a hidden"", It contains the information that should be appended to the URL .?
?
Session. cookie_lifetime = 0
The life cycle of the cookie file that saves sessionid. if the parameter is set to 0, the session ends, and the sessionid disappears automatically. if you close the browser forcibly, the last sessionid is lost;
?
Session. cookie_path =/
The location of the cookie file storing sessionid on the client;
?
Session. cookie_domain =/
The domain name setting of the cookie that saves sessionid is related to the access permission setting of the domain name allowed by the cookie. Generally, you want to allow all directories on your website to access the cookie on the client, set it to "/". For more information, see the setting and usage of the domain parameter of the setcookie () function;
?
Session. bug_compat_42 = 1
Session. bug_compat_warn = 1
These two settings can be said to be almost deprecated, mainly for the session_register function of the old php version, because the register_global function of php5 is disabled by default, so the session_register function is not used at all in php5; and php6 should abolish this setting and define it as disabled directly, so there is no need to study the two;


What does session_start () do?

Suppose several key parameters of session in php. ini are configured as follows:
Session. save_handler = files
Session. use_cookies = 1
Session. name = PHPSESSID
Session. save_path = "/tmp /"

?

The following code demonstrates the role of session_start in a session.

Procedure 1:
Session_start ();
$ _ SESSION ['uname'] = 'monkey ';
$ _ SESSION ['ukey'] = 20119999;
?>


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


1. generate a cookie file for storing PHPSESSID on the client. the storage location and storage method of this file are related to the execution method of the program, and different browsers are also different, in this step, a serialized string, PHPSESSID, is generated. you can view the cookie information in the browser and install related plug-ins. Httpfox and web developer are good tools in firefox.


2. a temporary file for storing session data is generated on the server end. the save_path parameter is specified. The name is similar to "secret". "sess _" indicates a session file. "85891d6a81ab13965d349bde29b2306c" indicates the PHPSESSID of the session, which is the same as the PHPSESSID value.
Open the "sess_85891d6a81ab13965d349bde29b2306c" file in the editor, and you will see a string of "uname | s: 6:" monkey "; ukey | I: 20119999. This file stores the specific content of the $ _ SESSION variable. each variable is separated by a semicolon.


The format is: variable name | variable type: [length]: value; for example: uname | s: 6: "monkey"; indicates that the SESSION variable uname type is a string, the value is 6 and the value is monkey.

So the question is: are the two things mentioned above completed when the program runs session_start? Who should be the first and later?
Let the test prove that a slight change to the program:

Procedure 2:
Session_start ();
$ _ SESSION ['uname'] = 'monkey ';
$ _ SESSION ['ukey'] = 20119999 ;?
?
Sleep (30 );
?>?

First, delete the session data of the client and the server, and then execute program 2. view the session information of the client and server with the sleep30 seconds in the program, and find: during program execution, the client does not create a cookie file for saving PHPSESSID, but the server has a temporary file for saving session content, but there is no content in the file, after 30 seconds, the cookie file on the client will be generated, and the session file on the server will have the content.


The general process is as follows: when the program runs to session_start (), the server first generates PHPSESSID and generates the corresponding session file, however, when the program assigns a value for $ _ SESSION, the corresponding value is not written into the session file. just assume that the value is stored in the memory. after the program is executed, the cookie file storing PHPSESSID is generated on the client, and the value in the $ _ SESSION variable is written into the session file of the server, there is no way to prove it.
?

To further demonstrate, delete the session-related content execution program of the client and server 3, and observe the results for the first and second times:
Procedure 3:
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'
'. $ _ SESSION ['uname'].'
';
Echo '***'. $ content .'***';
?>?
?

The above is the first execution method of sessin_start (), that is, what is done when the first session_start () occurs in a set of programs. let's look at the following session_start ():

Assume that the php. ini configuration is: session. cookie_lifetime = 0 ???????

Procedure 4:
Session_start ();?
Echo $ _ SESSION ['uname'];
Echo $ _ SESSION ['ukey'];
?>?

Now, the client has a cookie file for saving PHPSESSID, and the server also has the sess _ file for saving session content. execute program 4 and the normal content will be printed. In this case, what will happen if the browser is forcibly closed and program 4 is executed?

?

First, session. cookie_lifetime is set to 0, indicating that the life cycle of the cookie file that the client saves PHPSESSID is 0. if the browser is enabled, the PHPSESSID value is saved in the memory. Once disabled, the cookie file storing PHPSESSID will be destroyed at the same time, but session_destroy () is not executed on the server. Therefore, the session data file on the server is still running, but when the browser opens the execution program 4 again, I found that nothing was output, and thus the reasoning was:


Session_start () first obtains the PHPSESSID in the cookie on the client, and then forms a file name with "sess _", searches for the file on the server, and then retrieves the content in the file, put the content in the $ _ SESSION global variable for use. The browser is forced to close and then open. The previous PHPSESSID is lost. in this case, session_start () is equivalent to the first execution mentioned above, and a new PHPSESSID is generated, this PHPSESSID does not match the sess _ file of the previous server, so no content can be obtained. Of course, the server can also have a file that matches the PHPSESSID. However, the file is still empty.


Therefore, some systems can only log on to one machine or even one browser for the same user. if the session is not modified. when cookie_lifetime is set, the user cannot log on to the server before the session lifetime ends. a better way is to set the session. cookie_lifetime is set to a relatively large value. it does not affect the existence of a cookie file for a long time.

?

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.