: This article mainly introduces the principles and applications of HTTPsessioncookie in PHP. if you are interested in PHP tutorials, refer to it. PHP 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, which is similar to the header () function.
Bytes ------------------------------------------------------------------------------------------------------------------------------
1. set cookie:
A. You can use the setcookie () or setrawcookie () function to set the cookie. You can also set it by sending an http header directly to the client.
Eg:
Php code
- $ Value = 'something from somewhere ';
- Setcookie ("TestCookie", $ value);/* simple cookie setting */
- Setcookie ("TestCookie", $ value, time () + 3600);/* valid for 1 hour */
- Setcookie ("TestCookie", $ value, time () + 3600 ,"/~ Rasmus /",
- ".Example.com", 1);/* valid directory /~ Rasmus, valid domain name example.com and all its subdomains */
Set multiple cookie variables: setcookie ('Var [a] ', 'value'); use an array to represent variables, but its subscript is not enclosed in quotation marks. In this way, you can use $ _ COOKIE ['var'] ['A'] to read the COOKIE variable.
B. use header () to set the cookie;
Header ("Set-Cookie: name = $ value [; path = $ path [; domain = xxx.com [;...]");
Eg:
Php code
- $ Value = 'something from somewhere ';
- Header ("Set-Cookie: name = $ value ");
Bytes ------------------------------------------------------------------------------------------------------------------------------
2. read cookie:
Directly use php's built-in Super global variable $ _ COOKIE to read the cookie on the browser side.
The cookie "TestCookie" is set in the preceding example. now we can read:
Eg:
Php code
- Print $ _ COOKIE ['testcooker'];
Bytes ------------------------------------------------------------------------------------------------------------------------------
3. delete a cookie
Set the effective time to less than the current time, and set the value to null. For example:
Eg:
Php code
- Setcookie ("name", "", time ()-1 );
Similar to header.
Note:
A. An error message is prompted when setcookie () is used. it may be because there is an output or space before setcookie () is called. Or your document may be switched from another character set, and the document may be followed by a BOM signature (that is, add some hidden BOM characters to the file content ). The solution is to prevent this problem from occurring in your documents. You can also use the ob_start () function.
B. $ _ COOKIE is affected by magic_quotes_gpc and may be automatically escaped
C. It is necessary to test whether the user supports cookies.
Bytes ------------------------------------------------------------------------------------------------------------------------------
4. 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 from somewhere; path =/
The browser will create a cookie file on the disk of the client, and write:
TestCookie = something from somewhere;
This line is the result of using setcookie ('testcookie ', 'Something from somewhere. That is, use
Header ('set-Cookie: TestCookie = something from somewhere; path =.
------------------------------------------------- Split line --------------------------------------------------------------------
PHP SESSION
The session uses a cookie with the expiration time set to 0, and uses a unique identifier (a long string) called the session ID ), generate some session files synchronously on the server side (you can define the session storage type by yourself) and associate them with the user machine. The web application stores data related to these sessions and assigns a unique identifier (session ID) to visitors accessing the website as the data is transmitted between pages. It either stores the cookie on the client or passes the cookie through the URL. SESSION allows the user to register any number of variables and keep them for each request. When visitors visit the website, PHP will automatically (if session. auto_start is set to 1) or check whether a specific session id is sent in the request (explicitly called by session_start () or secretly called by session_register. If yes, the previously saved environment is rebuilt.
The core concept of a session is that the additional data for webpage jumps is stored on the server and identified by an id. to maintain the session, the browser must carry this id for each submission.
Bytes ------------------------------------------------------------------------------------------------------------------------------
The session id can be transmitted in two ways:
A. send the session id through cookie
Use session_start () to call the session. when the server generates the session file, it generates the session ID hash value and the session name with the default value PHPSESSID, and sends the variable (default) to the client) PHPSESSID (session name), with a 128-bit hash value. The server uses this cookie to interact with the client. The session variable value is serialized in php and stored in a text file on the server. it interacts with the coolie whose client variable name is PHPSESSID by default. that is, the server automatically sends the http header: header ('set-Cookie: session_name () = session_id (); path =/'); that is, setcookie (session_name (), session_id ());
After you jump to a new page from this page and call session_start (), PHP checks the session data stored on the server that is associated with the given ID. If no session data is found, a new dataset is created.
B. transmit the session ID through URL
This method is used only when the user disallows the use of cookies, because the browser cookie is already used. this method is not required for security purposes.
= "> Xxx, you can also pass the session value through POST.
Bytes ------------------------------------------------------------------------------------------------------------------------------
If the client prohibits the use of cookies, you can use the following methods:
A. set session. use_trans_sid = 1 in php. ini or enable the -- enable-trans-sid option when compiling, so that PHP can automatically pass the session id across pages.
B. manually pass session IDs through URL values and hidden forms.
C. Save the session_id in the form of files and databases and manually call it during the cross-page process.
Link: http://apps.hi.baidu.com/share/detail/41643457
Session can also be used when cookie is disabled:
In php. ini, when the session. use_cookies = 1 is changed to 0, the session will be saved on the server, rather than the cookie on the client.
You can use session. save_path to view the server's session storage location.
Session usage:
Eg:
Php code
- // Page1.php
- Session_start ();
- Echo 'Welcome to page #1 ';
- /* Create a session variable and assign a value to the session variable */
-
- $ _ SESSION ['favcolor'] = 'green ';
- $ _ SESSION ['Animal '] = 'cat ';
- $ _ SESSION ['Time'] = time ();
- // If the client uses cookies, the session can be directly transferred to page2.php.
- Echo'
Page 2 ';
- // If the client disables cookie
- Echo'
. SID. '"> page 2 ';
- /*
- By default, in php5.2.1, SID only has a value when the cookie is written.
- The corresponding cookie already exists, so the SID will be (undefined) null
- */
Php code
- // Page2.php
- Session_start ();
- Print $ _ SESSION ['Animal ']; // print a single session
- Var_dump ($ _ SESSION); // Print the session value passed by page1.php.
Delete session:
Eg:
Php code
- Session_destroy (); // Step 1: delete the session file on the server.
- Setcookie (session_name (), '', time ()-3600); // Step 2: delete an actual session:
- $ _ SESSION = array (); // Step 3: delete the $ _ SESSION global variable array
- ?>
Bytes ------------------------------------------------------------------------------------------------------------------------------
A simple example:
Php code:
Php code
- Session_start ();
-
- If (isset ($ _ SESSION ['test _ sess']) {
-
- $ _ SESSION ['test _ sess'] ++;
-
- } Else {
-
- $ _ SESSION ['test _ sess'] = 0;
-
- }
-
- Echo $ _ SESSION ['test _ sess'];
An http packet sniffing tool called httplook is used to capture packets:
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; MSIE 6.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.1 200 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; MSIE 6.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.1 200 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.
Summary:
Once the session is used, the session will be sent to the client browser through cookie.
In fact, session is an abstract concept. What session really wants to do is to target a user (possibly a browser, or a computer, or even an ip address), can save additional information. If we do not need the session provided by the system, we can transmit data completely. for example, we store the data in the session, serialize the data, and then encrypt it to form a string, it is passed in all URLs and forms on the page. After receiving the page request, the server extracts the secret string from get or post to uncover and restore the data, which is similar to what the session is about. However, this method is super bt, and too much extra work is required for implementation.
From a technical point of view, session refers to storing the additional data to be stored between webpage links with an id and stored on the server. the browser only needs to get or post each time, only this id is provided to obtain the previously stored data. By default, php uses files to store data. In unix, php generally creates a file name like "sess _" + $ session_id under/tmp. with this name, you can directly find the data corresponding to session_id. Therefore, the core concept of a session is to store additional data for webpage jumps on the server and identify it with an id. to maintain the session in the browser, this id is required for each submission.
How can I enable the browser to carry this id for each request? the stupid way is to add an id parameter to each url link or form post. some webmail actually does this. Of course, the simpler method is to save it through cookies. However, there is still a problem with the cookie solution. what if the browser does not support cookies.
The above session is the session function provided by php4 and 5. You must know that the system has not provided the session function before php4! In addition, many cgi programs are fully self-implemented sessions. Session provided by php (). by default, the system uses cookies to save session_id.
In my previous project, users used web in the intranet. To facilitate management, the browser ip address is directly bound to a session, that is, the sessionid is replaced by the browser ip address. There is no cookie in this solution, but it is still a session. it should be defined for him not to be removed from the session.
Each time a request is sent to the server, the local browser attaches the cookie to the request information.
In fact, it has nothing to do with the session. it only refers to how cookies work in the http protocol. This cookie is written by the session_start () function. you can write the cookie as long as it is written and does not exceed the validity period.
The above describes the principles and applications of the HTTP session cookie in PHP, including relevant content. I hope to help my friends who are interested in the PHP Tutorial.