PHP in Layman's session

Source: Internet
Author: User
Tags send cookies

1. Session Concept 0

2. HTTP protocol and status hold 0

3. Understanding Cookies 0

4. The session generation mechanism in PHP 2

5. The expiration recovery mechanism of the session in PHP 3

6. Client storage mechanism for session in PHP 4

1. Session Concept

In the era of Web server flourish, the semantics of session in the context of web development refers to a kind of solution to keep state between client and server.

2. HTTP protocol and status hold

The HTTP protocol itself is stateless, and the client simply requests to download certain files to the server, neither the client nor the server is required to record each other's past behavior, and each request is independent.
However, it was quickly discovered that providing some on-demand dynamic information would make the web more useful, just as it would be for a cable TV with on-demand functionality. This demand on the one hand, forcing HTML to gradually add the form, script, Dom and other client behavior, on the other hand on the server side of the CGI specification in response to the client's dynamic request, as a transport carrier HTTP protocol also added file upload, cookie these features. The purpose of the cookie is to resolve the HTTP protocol's stateless flaws in the efforts made. The subsequent session mechanism is another solution for maintaining state between the client and the server.

The session mechanism may need to use the cookie mechanism to achieve the purpose of preserving the identity. Therefore, it is necessary to understand the cookie.

3. Understanding Cookies

Cookie distribution is implemented by extending the HTTP protocol, and the server prompts the browser to generate the appropriate cookie by adding a special line of instructions to the HTTP response header. However, purely client-side scripts such as JavaScript or VBScript can also generate cookies.
And the use of cookies by the browser in accordance with certain principles in the background automatically sent to the server. The browser checks all stored cookies and, if a cookie declares a scope greater than or equal to the location of the resource to be requested, sends the cookie to the server on the HTTP request header of the requesting resource.
The contents of the cookie mainly include: name, value, expiration time, path and domain.
Where a domain can specify a domain such as. google.com, which is equivalent to the head office signs, such as the company, can also specify a domain under a specific machine such as www.google.com or froogle.google.com, can be used to make the ratio of fluttering. The path is the URL path that follows the domain name, such as/or/foo, and so on, can be used to do a certain float-soft counter.
The combination of the path and the domain constitutes the scope of the cookie.
If you do not set an expiration time, the cookie will not be in the lifetime of the browser session, as long as the browser window is closed. This cookie, which is the lifetime of the browser session, is referred to as a session cookie. Session cookies are generally not stored on the hard disk but are kept in memory, although this behavior is not regulated. If the expiration time is set, the browser will save the cookie to the hard disk, turn it off and open the browser again, and the cookies remain valid until the set expiration time is exceeded.
Cookies stored on the hard disk cannot be shared between different browsers and can be shared between different processes in the same browser, such as two IE windows.

This is because each browser stores cookies in a different location, such as

The cookies under Chrome are placed in:

C:\Users\sharexie\AppData\Local\Google\Chrome\User Data\default\cache

The cookie under Firefox is placed in:

C:\Users\sharexie\AppData\Roaming\Mozilla\Firefox\Profiles\tq2hit6m.default\cookies.sqlite (the penultimate filename is a random file name)

The cookies under IE are placed in:

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

(the internet says it's here, but I haven't found it)

I also have a test here that uses Httplook software to sniff under Firefox:

1. On this computer for the first time, open the Bing website, grab the package:

The returned data is as follows:

http/1.1 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%2C15DEB35B84A74788AE2D9978E3E657B1; 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, 11:35:50 GMT

content-length:12787

X-cache-lookup:miss from proxy:8080

We can see SessionID as 442e36abf8f5431e8dff0cac018437e3,domain for. Bing.com; Path is/. The server establishes a value for this user as a SID in a cookie session,id to 442e36abf8f5431e8dff0cac018437e3 as the client.

2, the second Request Bing website, request content as follows:

You see a cookie with the SID 442e36abf8f5431e8dff0cac018437e3 in the request.

The server returns data:

http/1.1 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, 11:41:12 GMT

content-length:12437

X-cache-lookup:miss from proxy:8080

Server view this TMP directory has a file name and Sid match, know is an old user, no new session, directly return data.

Of course there are a lot of 304 returns, which means that the user's cache can be used directly within the expires.

4. The session generation mechanism in PHP

Let's start by analyzing how a session is generated in PHP. The purpose of the session is to maintain the various states of each user to compensate for the lack of HTTP protocol (stateless). The session is saved on the server, since it is used to maintain the state of each user what does it use to differentiate users? This is the time to use cookies. When we call Session_Start () in the code, PHP generates a file for each of the session's directory (the default is/tmp/) and the client's cookie directory. The session file name looks like this:

The format is Sess_{sessionid}, when there is nothing in the session file, when we are in session_start (), add these two lines of code:

$_session[' name '] = ' sharexie ';

$_session[' webulr '] = ' www.qq.com ';

The file then has the content:

Name|s:8: "Sharexie"; Webulr|s:10: "Www.qq.com";

Then look at the cookie:

Can see the server for us automatically generated a cookie,cookie name called "Phpsessid", the cookie content is a string of characters, in fact, this string of characters is {SESSIONID}. When we use the session, PHP will be a unique SessionID number (such as 2bd170b3f86523f1b1b60b55ffde0f66), and then generate a file in our server's default directory, the file name is sess_{ SESSIONID}, while generating a cookie on the current user's client, the content has already been said. In this way, PHP generates a SessionID for each user, i.e. a session file for a user. When PHP first uses the session for a user, it writes a cookie to the client, and when the user accesses it, the browser takes the cookie,php and reads the SessionID in the cookie. Take this sessionid to the session directory to find the session file.

5. Outdated recovery mechanism for session in PHP

We understand how the session is generated and how it works, and found that there will be many session files in the Session directory. Of course, these files must not always exist, PHP must provide an outdated recovery mechanism. In PHP.ini, Session.gc_maxlifetime set the time to live for the session (default is 1440s). If the last update time of the session file is now more than the lifetime, the session file is considered to be out of date. It will be deleted when the next session is recycled. When is the next time the session is recycled? This is related to the number of PHP requests. In PHP internal mechanism, when PHP is requested n times, there will be a trigger recovery mechanism. Exactly how many times a request is triggered is controlled by the following two parameters:

session.gc_probability = 1

Session.gc_divisor = 100

This is the default setting for PHP.ini, which means that every 100 PHP requests are recycled at one time. The probability is gc_probability/gc_divisor (here I changed the session.gc_divisor to 1, as if the visit many times did not trigger the recycling event, do not know what reason). We understand the server-side session expiration mechanism, and then look at the client's cookie expiration mechanism.

If the cookie fails, the browser will naturally not be able to send cookies to the server, even if the server session file exists, because PHP does not know which session file to read. We know that PHP's cookie expiration is set at the time of creation, so how long does PHP create a cookie for the client while creating the session? This is set in php.ini: Session.cookie_lifetime. This value defaults to 0, which means that the browser shuts down SessionID. That means that if we set the Session.gc_maxlifetime and Session.cookie_lifetime to the same value, we can control the expiration time of the session.

6. Client storage mechanism for session in PHP

Since cookies can be artificially banned, there must be other mechanisms that can still pass the session ID back to the server when the cookie is banned. The solutions are:

1, url rewrite, is to attach the session ID directly behind the URL path, one is as the URL path of additional information, the representation of http://...../xxx;jsessionid= byok3vjfd75apnrf7c2hmdnv6qzcebzwowibyenlerjq99zwpbng!-145788764
2, the other is appended as a query string behind the URL, the representation of http://...../xxx?jsessionid=ByOK3vjFD75aPnrF7C2HmdnV6QZcEbzWoWiBYEnLerjQ99zWpBng!-145788764
These two ways for the user is no difference, but the server in the resolution of the way the process is different, the first way is also conducive to the session ID information and normal program parameters separated.
In order to maintain state throughout the interaction, the session ID must be included after each client may request a path.

3, Form hidden fields. Is that the server automatically modifies the form, adding a hidden field so that the session ID can be passed back to the server when the form is submitted. such as the following form
<form name= "Testform" action= "/xxx" >
<input type= "Text" >
</form>
will be rewritten before being passed to the client.
<form name= "Testform" action= "/xxx" >
<input type= "hidden" name= "Jsessionid" value= "byok3vjfd75apnrf7c2hmdnv6qzcebzwowibyenlerjq99zwpbng!-145788764" >
<input type= "Text" >
</form>
In fact, this technique can be replaced simply by applying URL rewriting to the action.

PHP in Layman's session

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.