PHP session and cookie

Source: Internet
Author: User
Tags http cookie php session

Php session Principle

Session is a way to maintain user session data on the server side. The corresponding cookie is to maintain user data on the client side. HTTP is a stateless protocol. After the server responds, it loses its connection with the browser. Cookies are introduced to the browser to enable data exchange across pages.

First, the client establishes a one-to-one connection with the server. Each client has a unique identifier so that the server can recognize the identity. We recommend that you use two unique identifiers: cookie or GET. By default, PHP uses session to create a cookie named "PHPSESSID" (you can use php. ini modifies the session. if the cookie is disabled on the client, you can also specify the GET method to transfer the session id to the server (modify php. session in ini. use_trans_sid and other parameters ).

The client passes the session id to the server. The server finds the corresponding file based on the session id. when reading the file, it deserializes the file content to obtain the session value. When saving the file, it serializes the file before writing it.

This is the case. If the server does not support the session or you want to customize the session, you can create a session id that never repeats through the uniqid of PHP, you can find a place to store the session content and store the session in the MySQL database.

The so-called session is actually a session id on the client. When a session file is created on the server, the server is told to generate a cookie and prepare the session file. Otherwise, how can the session content be stored; tell the server when reading the session and deserialize the session file according to the session id.

Session affects system performance

Session does affect system performance on websites with high traffic. One of the reasons that affect performance is caused by the file system design. When there are more than 10000 files under the same directory, file locating takes a lot of time, PHP supports session directory hash. We can modify php. session in ini. save_path = "2;/path/to/session/dir", the session will be stored in two subdirectories, each of which has 16 subdirectories [0 ~ F], but it seems that PHPsession does not support creating directories. You need to create these directories in advance.

Another problem is the efficiency of small files. Generally, our session data is not too large (1 ~ 2 K), if there are a large number of such 1 ~ 2 k files are stored on the disk, and the IO efficiency is definitely poor. You can cache memcache and mysql databases to provide efficiency.

Session Synchronization

There may be many front-end servers. Users have logged on to server A and planted session information. Then, some pages on the website may jump to server B, if there is no session information on server B and no special processing is performed at this time, a problem may occur.

There are many kinds of session synchronization. If you store them in memcached or MySQL, it is easy to specify the same location. If it is in the file format, you can use NFS for Unified Storage.

(NFS is short for Network File System, that is, Network File System. the Network File System is one of the file systems supported by FreeBSD, also known as NFS. NFS allows a system to share directories and files with others on the network. By using NFS, users and programs can access files on the remote system just like accessing local files .)

Another way is to use encrypted cookies. After A user successfully logs on to server A, an encrypted cookie is added to the browser. When A user accesses server B, check whether there is a session. If yes, check whether the cookie is valid. If yes, re-create the session on server B. This method is actually very useful. If the website has many sub-channels and the server is not in the same data center, the session cannot be synchronized and it is too useful to achieve unified login.

Of course, another way is to maintain the session at the layer of Server Load balancer and bind the visitor to a server. All the accesses to the server do not require session synchronization.


<? Php

Session_start ();

If (isset ($ _ SESSION ['test _ sess']) {

$ _ SESSION ['test _ sess'] ++;

} Else {

$ _ SESSION ['test _ sess'] = 0;

}

Echo $ _ SESSION ['test _ sess'];

?>;

First Request Server:

GET/test. php HTTP/1.1

Accept :*/*

Referer: http: // localhost/

Accept-Language: zh-cn

Accept-Encoding: gzip, deflate

User-Agent: Mozilla/4.0 (compatible; MSIE6.0; Windows NT 5.1; SV1; Maxthon;. net clr 1.1.4322)

Host: localhost

Connection: Keep-Alive

The first time the server returns:

HTTP/1.1200 OK

Date: Fri, 26 Aug 2005 07:44:22 GMT

Server: Apache/2.0.54 (Win32) SVN/1.2.1 PHP/5.0.4 DAV/2

X-Powered-By: PHP/5.0.4

Set-Cookie: PHPSESSID = bmmc3mfc94ncdr15ujitjogma3; path =/

Expires: Thu, 19 Nov 1981 08:52:00 GMT

Cache-Control: no-store, no-cache, must-revalidate, post-check = 0, pre-check = 0

Pragma: no-cache

Content-Length: 1

Keep-Alive: timeout = 15, max = 99

Connection: Keep-Alive

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

Content-Language: Off

Second request Server:

GET/test. php HTTP/1.1

Accept :*/*

Referer: http: // localhost/

Accept-Language: zh-cn

Accept-Encoding: gzip, deflate

User-Agent: Mozilla/4.0 (compatible; MSIE6.0; Windows NT 5.1; SV1; Maxthon;. net clr 1.1.4322)

Host: localhost

Connection: Keep-Alive

Cookie: PHPSESSID = bmmc3mfc94ncdr15ujitjogma3

The second response from the server:

HTTP/1.1200 OK

Date: Fri, 26 Aug 2005 07:44:23 GMT

Server: Apache/2.0.54 (Win32) SVN/1.2.1 PHP/5.0.4 DAV/2

X-Powered-By: PHP/5.0.4

Set-Cookie: PHPSESSID = bmmc3mfc94ncdr15ujitjogma3; path =/

Expires: Thu, 19 Nov 1981 08:52:00 GMT

Cache-Control: no-store, no-cache, must-revalidate, post-check = 0, pre-check = 0

Pragma: no-cache

Content-Length: 1

Keep-Alive: timeout = 15, max = 98

Connection: Keep-Alive

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

Content-Language: Off

By carefully comparing these outputs, the second request is more than the first request:

Cookie: PHPSESSID = bmmc3mfc94ncdr15ujitjogma3

This header will send a cookie to the server, telling the server that there is a cookie named PHPSESSID with the content bmmc3mfc94ncdr15ujitjogma3.

How does this cookie come from? The information returned by the first Server includes:

Set-Cookie: PHPSESSID = bmmc3mfc94ncdr15ujitjogma3; path =/

This is a cookie written by the server to the client browser. The name is PHPSESSID and the value is bmmc3mfc94ncdr15ujitjogma3. The value is actually the so-called session_id.

The second request sent to the server still sends the PHPSESSID cookie to the server.

The following conclusions can be obtained:

1. If session is used, the session will be sent to the client browser through cookie.

2. Each time a request is sent to the server, the local browser attaches the cookie to the request information.

COOKIE

Cookie is a mechanism for storing data in a remote browser and tracking and identifying users.

PHP sends cookies in the http header. Therefore, the setcookie () function must be called before other information is output to the browser.

Principle.

A. the server sends an http Set-Cookie header in response and sets a cookie in the client (multiple cookies have multiple heads ).

B. The client automatically sends an http cookie header to the server, and the server receives and reads the cookie.

HTTP/1.x 200 OK

X-Powered-By: PHP/5.2.1

Set-Cookie: TestCookie = something from somewhere; path =/

Expires: Thu, 19 Nov 2007 18:52:00 GMT

Cache-Control: no-store, no-cache, must-revalidate, post-check = 0, pre-check = 0

Pragma: no-cache

Content-type: text/html

This line implements the cookie function. After receiving this line

Set-Cookie: TestCookie = something fromsomewhere; path =/

The browser creates a cookie file on the client disk.

The following results show the same effect:

Setcookie ('testcookie ', 'something from somewhere ','/');

Header ('set-Cookie: TestCookie = something from somewhere; path = /')

FAQs:

1) An error message is prompted when setcookie () is used, probably because there is an output or space before setcookie () is called.

2) $ _ COOKIE is affected by magic_quotes_gpc and may be automatically escaped.

3) it is necessary to test whether the user supports cookies.

The following uses user logon as an example to analyze session and cookie

HTTP is a stateless protocol. After the server responds to a user's request, it loses connection with the browser and PHP implements the session.

When a user accesses the server for the first time, because there is no session information, the user needs to log on for verification. The user submits the user name, password, verification code, and other information to the server through the form, the server processes the data before verifying the validity of the user. The user is valid when it passes database verification. At this time, the server will include the Set-Cookie: PHPSESSID = bmmc3mfc94ncdr15ujitjogma3 in the browser information, in this way, the browser writes the information to the local file, where PHPSESSID is a unique identifier. At the same time, the server will save the serialized session information in the file in the specified file. When the user requests again, the browser will also send the PHPSESSID in the corresponding cookie to the server. The server will get PHPSESSID, which will be verified in the session file. If the verification is successful, log on directly. Similarly, data can be transmitted before different user pages. The value in the session is key-value.

Session affects system performance

Session does affect system performance on websites with high traffic. One of the reasons that affect performance is caused by the file system design. When there are more than 10000 files under the same directory, file locating takes a lot of time, PHP supports session directory hash. We can modify php. session in ini. save_path = "2;/path/to/session/dir", the session will be stored in two subdirectories, each of which has 16 subdirectories [0 ~ F], but it seems that PHPsession does not support creating directories. You need to create these directories in advance.

Another problem is the efficiency of small files. Generally, our session data is not too large (1 ~ 2 K), if there are a large number of such 1 ~ 2 k files are stored on the disk, and the IO efficiency is definitely poor. You can cache memcache and mysql databases to provide efficiency.

Session Synchronization

There may be many front-end servers. Users have logged on to server A and planted session information. Then, some pages on the website may jump to server B, if there is no session information on server B and no special processing is performed at this time, a problem may occur.

There are many kinds of session synchronization. If you store them in memcached or MySQL, it is easy to specify the same location. If it is in the file format, you can use NFS for Unified Storage.

(NFS is short for Network File System, that is, Network File System. the Network File System is one of the file systems supported by FreeBSD, also known as NFS. NFS allows a system to share directories and files with others on the network. By using NFS, users and programs can access files on the remote system just like accessing local files .)

Another way is to use encrypted cookies. After A user successfully logs on to server A, an encrypted cookie is added to the browser. When A user accesses server B, check whether there is a session. If yes, check whether the cookie is valid. If yes, re-create the session on server B. This method is actually very useful. If the website has many sub-channels and the server is not in the same data center, the session cannot be synchronized and it is too useful to achieve unified login.

Another way is to maintain the session at the layer of Server Load balancer and bind the visitor to a server. All other accesses are not required on that server.

 

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.