Php session-jerrylsxu

Source: Internet
Author: User
Tags php session
Php: session-jerrylsxu 1. session concept 0

2. http protocol and status remain 0

3. understand cookie 0

4. session generation mechanism in php 2

5. php session expiration mechanism 3

6. session client storage mechanism in php 4

1. session concept

In the era of vigorous development of web servers, session semantics in the web development context refers to a type of solution for maintaining the status between the client and the server.

2. http protocol and status persistence

The http protocol itself is stateless. the client simply needs to request to download some files from the server, and neither the client nor the server needs to record the previous behaviors of each other, each request is independent.
However, it is quickly discovered that providing dynamic information generated on demand will make the web more useful, just like adding the on-demand function to cable TV. On the one hand, this requirement forces HTML to gradually add client behaviors such as forms, scripts, and DOM, and on the other hand, there is a CGI specification on the server side to respond to dynamic requests from the client, the HTTP protocol, which acts as the transmission carrier, also adds the file upload and cookie features. Among them, cookies are used to solve the stateless defects of HTTP. As for the later session mechanism, it is another solution that maintains the status between the client and the server.

The session mechanism may need the cookie mechanism to save the identity. Therefore, it is necessary to understand the cookie.

3. understand cookies

Cookie distribution is implemented by extending the HTTP protocol. by adding a special line of instructions to the HTTP response header, the server prompts the browser to generate the corresponding cookie according to the instructions. However, pure client scripts such as JavaScript or VBScript can also generate cookies.
Cookies are automatically sent to the server in the background by the browser according to certain principles. The browser checks all stored cookies. if the declared range of a cookie is greater than or equal to the location where the requested resource is located, the cookie is attached to the HTTP request header of the requested resource and sent to the server.
Cookie content mainly includes: name, value, Expiration Time, path and domain.
The domain can specify a domain such as .google.com, which is equivalent to a main store sign. for example, Procter & Gamble can also specify a specific machine in a domain such as www.google.com or froogle.google.com, you can use rejoice for comparison. The path is the URL path following the domain name, for example, // or/foo. you can use a certain rejoice counter to compare it.
The combination of paths and domains constitutes the scope of cookie.
If no expiration time is set, it indicates that the life cycle of the cookie is the browser session period. when the browser window is closed, the cookie disappears. This cookie is called a session cookie. Session cookies are generally stored in the memory instead of on the hard disk. of course, this behavior is not standardized. If the Expiration Time is set, the browser will save the cookie to the hard disk, close it, and open the browser again. These cookies are still valid until the preset expiration time is exceeded.
Cookies stored on hard disks cannot be shared between different browsers. they can be shared between different processes in the same browser, such as two IE windows.

This is because each browser stores different cookies, such

Put the cookie in Chrome:

C: \ Users \ sharexie \ AppData \ Local \ Google \ Chrome \ User Data \ Default \ Cache

Put the cookie in Firefox in:

C: \ Users \ sharexie \ AppData \ Roaming \ Mozilla \ Firefox \ Profiles \ tq2hit6m. default \ cookies. sqlite (the last and last file names are random file names)

Put the cookie in Ie:

C: \ Users \ Administrator \ AppData \ Roaming \ Microsoft \ Windows \ Cookies

(It is said on the Internet, but I have never found it)

I also have a test here. in firefox, I use httplook for sniffing:

1. start the Bing website for the first time on the local machine and capture packets:

The returned data is as follows:

HTTP/1.1 200 OK

Cache-Control: private, max-age = 0

Content-Type: text/html; charset = utf-8

Content-Encoding: gzip

Set-Cookie: _ FS = NU = 1; domain = .bing.com; path =/

Set-Cookie: _ SS = SID = 442E36ABF8F5431E8DFF0CAC018437E3; domain = .bing.com; path =/

Set-Cookie: MUID = 32B1FE9DB0EB65B52006FD50B1E86565; expires = Sun, 31-Aug-2014 11:35:51 GMT; domain = .bing.com; path =/

Set-Cookie: OrigMUID = 32B1FE9DB0EB65B52006FD50B1E86565% Others; expires = Sun, 31-Aug-2014 11:35:51 GMT; domain = .bing.com; path =/

Set-Cookie: SRCHD = D = 2454455 & MS = 2454455 & AF = NOFORM; expires = Sun, 31-Aug-2014 11:35:51 GMT; domain = .bing.com; path =/

Set-Cookie: SRCHUID = V = 2 & GUID = F6DCC04B2CC54139928925763DAEE04A; expires = Sun, 31-Aug-2014 11:35:51 GMT; path =/

Set-Cookie: SRCHUSR = AUTOREDIR = 0 & GEOVAR = & DOB = 20120831; expires = Sun, 31-Aug-2014 11:35:51 GMT; domain = .bing.com; path =/

P3P: CP = "non uni com nav sta loc CURa DEVa PSAa PSDa our ind"

Date: Fri, 31 Aug 2012 11:35:50 GMT

Content-Length: 12787

X-Cache-Lookup: MISS from proxy: 8080

We can see that sessionId is 442E36ABF8F5431E8DFF0CAC018437E3, domain is .bing.com; path is /. The server creates a session for this user with the id 442E36ABF8F5431E8DFF0CAC018437E3 as the SID value in the customer service cookie.

2. for the second request, go to the Bing website. The request content is as follows:

The request contains a cookie with sid 442E36ABF8F5431E8DFF0CAC018437E3.

Data returned by the server:

HTTP/1.1 200 OK

Cache-Control: private, max-age = 0

Content-Type: text/html; charset = utf-8

Content-Encoding: gzip

P3P: CP = "non uni com nav sta loc CURa DEVa PSAa PSDa our ind"

Date: Fri, 31 Aug 2012 11:41:12 GMT

Content-Length: 12437

X-Cache-Lookup: MISS from proxy: 8080

The server checks that the name of a file in the tmp directory matches the SID. it knows that the file is an old user and no session is created. data is directly returned.

Of course, there are also many 304 responses, indicating that you can directly use the user's cache in expires.

4. session generation mechanism in php

Let's analyze how a session is generated in PHP. The purpose of the session design is to maintain the various statuses of each user to make up for the shortcomings of the HTTP protocol (stateless ). The session is stored on the server. since it is used to maintain the state of every user, what is the difference between the session and the user? At this time, we need to use cookies. When session_start (); is called in the code, PHP will generate a file for each SESSION's storage directory (/tmp/by default) and the client's cookie directory. The session file name is as follows:

The format is sess _ {SESSIONID}. in this case, the session file does not contain any content. when we add these two lines of code in session_start:

$ _ SESSION ['name'] = 'sharexie ';

$ _ SESSION ['webulr'] = 'www .qq.com ';

The file contains the following content:

Name | s: 8: "sharexie"; webUlr | s: 10: "www.qq.com ";

Now let's look at the cookie:

We can see that the server automatically generates a cookie named "PHPSESSID". The cookie content is a string of characters, which are actually {SESSIONID }. When we use session, PHP will generate a unique SESSIONID (such as 2bd170b3f86523f1b1b60b55ffde0f66), and then generate a file named sess _ {SESSIONID} in the default directory of our server }, at the same time, a cookie is generated on the client of the current user. the content has already been said. In this way, PHP generates a session id for each user, that is, a session file for each user. PHP writes a cookie to the client when a user uses the session for the first time. when the user accesses the session later, the browser will carry the cookie. after receiving the cookie, PHP will read the SESSIONID, take this SESSIONID to the session directory to find the session file.

5. php session expiration mechanism

We understand the session generation and working principles and find that there are many session files in the session directory. Of course, these files do not always exist. PHP must provide an expiration recycle mechanism. In php. ini, session. gc_maxlifetime sets the session survival time (1440 s by default ). If the last update time of the session file exceeds the survival time, the session file is considered to have expired. The next session will be deleted. When will the next session be recycled? This is related to the number of php requests. In the internal mechanism of PHP, When php is requested for N times, a recycle mechanism will be triggered once. The following two parameters are used to control how many requests are triggered:

Session. gc_probability = 1

Session. gc_pisor = 100

This is the default setting of php. ini, which means that every 100 PHP requests are recycled once. The probability is gc_probability/gc_pisor (here I change session. gc_pisor to 1. it seems that the collection event is not triggered many times and I don't know why ). We have learned about the session expiration mechanism on the server side. let's take a look at the cookie expiration mechanism on the client side.

If the cookie fails, the browser will naturally fail to send the cookie to the server. in this case, even if the server's session file exists, PHP does not know which session file to read. We know that the expiration time of the PHP cookie is set at the time of creation. How long is the lifecycle of the cookie created for the client when the PHP creates the session? This is set in php. ini: session. cookie_lifetime. The default value is 0, indicating that the browser will expire when SESSIONID is disabled. That is to say, we can set session. gc_maxlifetime and session. cookie_lifetime to the same value to control the session expiration time.

6. session client storage mechanism in php

Because cookies can be artificially disabled, there must be other mechanisms so that session IDs can still be passed back to the server when cookies are disabled. Solutions:

1. URL rewriting is to directly append the session id to the end of the URL path. one is the additional information of the URL path, in the form of http ://..... /xxx; jsessionid = ByOK3vjFD75aPnrF7C2HmdnV6QZcEbzWoWiBYEnLerjQ99zWpBng! -145788764
2. the other is appended to the URL as a query string, in the form of http: //.../xxx? Jsessionid = ByOK3vjFD75aPnrF7C2HmdnV6QZcEbzWoWiBYEnLerjQ99zWpBng! -145788764
There is no difference between the two methods for users, but they are handled differently by servers during parsing, the first method also helps to distinguish the session id information from the normal program parameters.
To maintain the status throughout the interaction process, the session id must be included after the path that each client may request.

3. hidden fields in the form. The server automatically modifies the form and adds a hidden field so that the session id can be passed back to the server when the form is submitted. For example, the following form

It will be rewritten

In fact, this technology can be simply replaced by rewriting the URL of the action application.

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.