PHP Session and cookie_php tutorial

Source: Internet
Author: User
Tags http cookie session id php session setcookie
PHP Session Principle

Session is a way to keep user session data on the server side, and the corresponding cookie is to keep the user data on the client. HTTP protocol is a stateless protocol, the server after the response has lost the connection with the browser, the cookie into the browser, so that the data across the page exchange.

First, the client and server establish one by one connections, each client has a unique identity, so that the server can be recognized. There are two ways to suggest a unique identity: a cookie or a get specified. The default configuration of PHP when using the session will create a "PHPSESSID" cookie (can be specified by php.ini modify the Session.name value), if the client disables cookies, you can also specify by the get way to the session ID to the server (modify parameters such as Session.use_trans_sid in php.ini).

The client passes the session ID to the server, the server finds the corresponding file according to the session ID, and when it is read, the contents of the file are deserialized to get the value of the session, and the time to save is serialized and then written.

This is the case, if the server does not support the session or you want to customize the session, can be completely DIY, through the PHP uniqid to generate the session ID never repeat, and then find a place to store the contents of the session, You can also store the session in the MySQL database.

The so-called session is actually a client session ID, server side A session file, the new session, tell the server to generate a cookie and prepare the session file, otherwise your session content how to save Read the session, tell the server, quickly according to the session ID to deserialize the session file.

Session affects system performance

Session on the large traffic site does affect the performance of the system, one of the reasons for performance is caused by the file system design, in the same directory more than 10,000 files, the location of the file will be very time-consuming, PHP support Session Directory hash, We can modify php.ini in Session.save_path = "2;/path/to/session/dir", then the session will be stored in the level two subdirectory, each directory has 16 subdirectories [0~f], However, it seems that phpsession does not support creating directories, you need to create them in advance.

Another problem is the efficiency of small files, generally our session data is not too large (1~2k), if there are a large number of such 1~2k files on disk, IO efficiency will certainly be poor. Efficiency can be provided by caching memcache and MySQL databases.

Synchronization of Session

The front-end may have many servers, the user logged on a server, planted the session information, and then visit some pages of the site might jump to B server up, if this time the B server does not have session information and do not do special treatment, it may be a problem.

There are many kinds of session synchronization, if you are stored in memcached or MySQL, it is very easy to specify to the same location, if it is in the form of files, you can use NFS Unified storage.

(NFS is a shorthand for the network file system, that is, the web filesystem.) 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 as if they were accessing local files. )

There is also a way to achieve through the encryption of cookies, the user on a server login success, the user's browser to type an encrypted cookie, when the user visited the B server, check whether the session, if there is no problem, if not, to verify that the cookie is valid, If the cookie is valid, the session is rebuilt on the B server. This method is actually very useful, if the site has a lot of sub-channels, the server is not a room, the session can not be synchronized and want to do a unified login that is too useful.

Of course, one way is to keep the session on the Load Balancer layer, bind the visitor to a server, and all of his accesses will not need to be synchronized with the session on that server.


Session_Start ();

if (Isset ($_session[' test_sess ')) {

$_session[' test_sess ']++;

}else{

$_session[' test_sess '] = 0;

}

echo$_session[' test_sess '];

?>;

The first time the server is requested:

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 server returns for the first time:

http/1.1200 OK

Date:fri, 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, 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 server returns for the second time:

http/1.1200 OK

Date:fri, 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, 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

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

Cookie:phpsessid=bmmc3mfc94ncdr15ujitjogma3

This header will send a cookie message to the server telling the server that I have a cookie named Phpsessid, which is bmmc3mfc94ncdr15ujitjogma3.

How did this cookie come about? Look at the first time the server returned the information inside:

SET-COOKIE:PHPSESSID=BMMC3MFC94NCDR15UJITJOGMA3; path=/

This is the server to the client browser to write a cookie, the name is PHPSESSID, the value is BMMC3MFC94NCDR15UJITJOGMA3, this value is actually called session_id.

Continue to see the second request to the server, still sent to the server Phpsessid this cookie

The following conclusions can be obtained:

1. If the session is used, the session will be sent to the client browser by means of a cookie

2. Each time a request is made to the server, the local browser will attach the cookie to the request message.

Cookies

A cookie is a mechanism for storing data on a remote browser to track and identify users.

PHP sends a cookie in the header of the HTTP protocol, so the Setcookie () function must be called before other information is exported to the browser.

Principle.

A. The server sets a cookie (multiple cookies are more than one) in the client computer by sending an HTTP Set-cookie header in response.

B. The client automatically sends an HTTP cookie header to the server, and the server receives the read.

http/1.x OK

x-powered-by:php/5.2.1

Set-cookie:testcookie=something from somewhere; path=/

Expires:thu, 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 row

Set-cookie:testcookie=something Fromsomewhere; path=/

The browser will create a cookie file on the client's disk.

Here's the same effect:

Setcookie (' TestCookie ', ' Something from somewhere ', '/');

Header (' set-cookie:testcookie=something from somewhere; path=/')

Frequently asked questions resolved:

1) There is an error when using Setcookie (), possibly because there is an output or a space in front of the call Setcookie ().

2) $_cookie is affected by MAGIC_QUOTES_GPC and may be automatically escaped.

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

The following is an example of user login analysis session and Cookie

HTTP protocol is a stateless protocol, the server responds to the user's request, lost the connection with the browser, how PHP implementation session.

When the user first accesses the server, because there is no session information, need to login authentication, the user through the form to the user name, password, verification code and other information submitted to the server, the server in verifying the legitimacy of the user before the data preprocessing. Through to the database authentication, the user is legitimate, this time the server will give the browser information contains SET-COOKIE:PHPSESSID=BMMC3MFC94NCDR15UJITJOGMA3, such information, so that the browser will write the information into a local file, Where PHPSESSID is a unique identifier. The server also saves the serialized session information in the file in the specified file. When the user requests again, the browser will send the corresponding cookie PHPSESSID also sent to the server, the server gets PHPSESSID, will be verified in the session file, if the authentication is successful, log in directly. This enables similar data to be passed on to different user pages. The value in the session is Key-value.

Session affects system performance

Session on the large traffic site does affect the performance of the system, one of the reasons for performance is caused by the file system design, in the same directory more than 10,000 files, the location of the file will be very time-consuming, PHP support Session Directory hash, We can modify php.ini in Session.save_path = "2;/path/to/session/dir", then the session will be stored in the level two subdirectory, each directory has 16 subdirectories [0~f], However, it seems that phpsession does not support creating directories, you need to create them in advance.

Another problem is the efficiency of small files, generally our session data is not too large (1~2k), if there are a large number of such 1~2k files on disk, IO efficiency will certainly be poor. Efficiency can be provided by caching memcache and MySQL databases.

Synchronization of Session

The front-end may have many servers, the user logged on a server, planted the session information, and then visit some pages of the site might jump to B server up, if this time the B server does not have session information and do not do special treatment, it may be a problem.

There are many kinds of session synchronization, if you are stored in memcached or MySQL, it is very easy to specify to the same location, if it is in the form of files, you can use NFS Unified storage.

(NFS is a shorthand for the network file system, that is, the web filesystem.) 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 as if they were accessing local files. )

There is also a way to achieve through the encryption of cookies, the user on a server login success, the user's browser to type an encrypted cookie, when the user visited the B server, check whether the session, if there is no problem, if not, to verify that the cookie is valid, If the cookie is valid, the session is rebuilt on the B server. This method is actually very useful, if the site has a lot of sub-channels, the server is not a room, the session can not be synchronized and want to do a unified login that is too useful.

Another way is to keep the session on the Load Balancer layer, bind the visitor to a server, and all other accesses are not required on that server.

http://www.bkjia.com/PHPjc/477521.html www.bkjia.com true http://www.bkjia.com/PHPjc/477521.html techarticle The PHP session principle session is a way to keep user session data on the server side, and the corresponding cookie is to keep the user data on the client. HTTP protocol is a stateless protocol, 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.