PHP's Cookie
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, similar to the limit on the header () function.
--------------------------------------------------------------------------------------------------------------- ---------------
1. Set Cookies:
A. You can use the Setcookie () or Setrawcookie () function to set cookies. It can also be set by sending HTTP headers directly to the client.
eg
PHP code
- $value = Something from somewhere ';
- setcookie ( $value) /* simple cookie settings */
- setcookie ( $value, time ( ) +3600); /* valid 1 hours */
- Setcookie ( $value, time () +3600,
- /* valid directory /~rasmus, valid domain example.com and all sub-domains */
Set multiple cookie variables: Setcookie (' var[a] ', ' value '); The variable is represented by an array, but his subscript is not quoted. This allows you to use $_cookie[' var ' [' a '] to read the COOKIE variable.
B. Use the header () to set the cookie;
Header ("Set-cookie:name= $value [;p ath= $path [;d omain=xxx.com[; ...]];
eg
PHP code
- $value = ' something from somewhere ';
- Header ("Set-cookie:name= $value");
--------------------------------------------------------------------------------------------------------------- ---------------
2. Read the cookie:
The browser-side COOKIE can be read directly with PHP's built-in Super global variable $_cookie.
The above example sets the cookie "TestCookie" and now we are reading:
eg
PHP code
- Print $_cookie[' TestCookie '];
--------------------------------------------------------------------------------------------------------------- ---------------
3. Delete Cookies
Just set the valid time to less than the current time, and leave the value blank. For example:
eg
PHP code
- Setcookie ("name", " ", Time ()-1);
Similar to the header ().
Note
A. There is an error when using Setcookie (), possibly because an output or a space precedes the call to Setcookie (). It may also be that your document is converted from another character set, and the document may be followed by a BOM signature (that is, adding some hidden BOM characters to the contents of the file). The solution is to keep your documents from happening. There is also the ability to handle a point by using the Ob_start () function.
B.$_cookie affected by MAGIC_QUOTES_GPC, may be automatically escaped
C. When using, it is necessary to test whether the user supports cookies
--------------------------------------------------------------------------------------------------------------- ---------------
4. 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 from somewhere; path=/
The browser creates a cookie file on the client's disk and writes it inside:
Testcookie=something from somewhere;
This line is what we use Setcookie (' TestCookie ', ' Something from somewhere ', '/'); The result. That means using
Header (' set-cookie:testcookie=something from somewhere; path=/'); results.
-------------------------------------------------Split Line--------------------------------------------------------------------
The session of PHP
The session uses a cookie that has an expiration time of 0, and a unique identifier called the session ID (a long string of strings), which in the server-side synchronization generates some session files (which can define the save type of the session itself), linked to the user's office. The Web application stores the data associated with these sessions and lets the data pass along with the user across the page. Visitors to the site are assigned a unique identifier, the so-called session ID. It is either stored on the client's cookie or passed through the URL. SESSION allows the user to register any number of variables and keep them for use by each request. When a visitor visits a website, PHP automatically (if Session.auto_start is set to 1) or when requested by session_start () or Session_register () Secretly called) to check whether a specific session ID was sent in the request. If it is, the previously saved environment is rebuilt.
The most important concept of the session is: the extra data of the jump between pages, stored in the server, with an ID, the browser to maintain the session, each commit to take this ID.
--------------------------------------------------------------------------------------------------------------- ---------------
There are two ways to pass the session ID:
A. Transferring SESSION ID via cookie
Using Session_Start () Call session, the server side generates session ID hash value and the default value is PHPSESSID session name, and sends the variable to the client (default). PHPSESSID (session name), the value is a 128-bit hash value. The server side will interact with the client through this cookie. The value of the session variable is stored in a text file on the server machine after PHP is serialized internally, and the client's variable name is PHPSESSID by default for Coolie. That is, the server automatically sends an HTTP header: header (' Set-cookie: Session_name () =session_id (); path=/'); namely Setcookie (Session_name (), session_id ());
When a new page jumps from the page and calls Session_Start (), PHP checks the session data for the server-side storage associated with the given ID, and creates a new dataset if it is not found.
B. Pass the session ID via URL
This method is only used when the user prohibits the use of cookies, as browser cookies are already common and are not available for security purposes.
<a href= "p.php?<?php print session_name () >=<?php print session_id ()?>" >XXX</A> To pass the session value.
--------------------------------------------------------------------------------------------------------------- ---------------
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 open the--ENABLE-TRANS-SID option at compile time to have PHP automatically pass the session ID across pages.
b, manually pass the URL value, hide the form passing session ID.
c, file, database and other forms to save session_id, in the process of cross-page calls manually.
link:http://apps.hi.baidu.com/share/detail/41643457
The session can also be used when cookies are disabled:
PHP.ini in Session.use_cookies=1, instead 0,session will be saved on the server side, not the client's cookie.
You can view the server's session storage location via Session.save_path.
Use of Session:
eg
PHP code
- page1.php
- Session_Start ();
- echo ' Welcome to page #1 ';
- / * Create session variable and assign value to session variable * /
- $_session[' favcolor '] = ' green ';
- $_session[' animal ' = ' cat ';
- $_session[' time ' = time ();
- //If the client uses cookies, it can pass the session directly to page2.php
- echo ' <br/><a href= "page2.php" >page 2</a> ';
- //If the client disables cookies
- echo ' <br/><a href= ' page2.php? '. Sid. ' >page 2</a> ';
- /*
- By default php5.2.1, the SID will have a value only if the cookie is written, if the session
- The corresponding cookie already exists, then the SID will be (undefined) null
- */
PHP code
- page2.php
- Session_Start ();
- Print $_session[' animal ']; //Print out a single session
- Var_dump ($_session); //Print out the session value passed by page1.php.
Delete session:
eg
PHP code
- Session_destroy (); ///First step: Delete the server-side session file, which uses
- Setcookie (Session_name (),", Time ()-3600); ///Step Two: Delete the actual session:
- $_session = Array (); //Step three: Delete $_session global variable array
- ?>
--------------------------------------------------------------------------------------------------------------- ---------------
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 '];
Use an HTTP packet sniffer tool called Httplook to grab the package:
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; MSIE 6.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.1 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; MSIE 6.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.1 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.
Summarize:
Whenever a session is used, the session is sent to the client browser by means of a cookie
The session is actually an abstract concept, and what the session really does is save extra information for a user (probably a browser, or a computer, or even an IP) in addition to the parameters provided by the Get and post supplied by HTTP. If we do not use the session provided by the system, we can pass the data completely, such as the data we originally want to save session, serialize and then encrypt, form a string, on the page all the URL and form passed. When the server receives a page request, it removes the secret string from the Get or post, uncovers and restores the data, in fact the same thing as the session. Just this way super BT, to achieve the need to do too much extra work.
The session from a technical point of view, is to link between the Web page, the additional data to be stored, named after an ID, saved on the server side, and the browser only need to get or post each time the appropriate, only provide this ID, you can obtain the data stored previously. PHP uses files to save data by default. Under UNIX, PHP generally under/tmp, create "Sess_" + $session _id such a file name, through this name, you can directly find session_id corresponding data. So the most important concept of the session is: the extra data between pages, stored in the server, with an ID identifier, the browser to maintain the session, each commit to take this ID.
How can let the browser each request can carry this ID, the stupid method is of course in each URL link or form of the post to add an ID parameter, some webmail actually do this. Of course, the simpler way is to save it through a cookie. However, there is a problem with the cookie scheme, which is also stated if the browser does not support cookies.
The session above, is php4,5 provides the session function, to know PHP4 before the system did not provide session function! And a lot of CGI programs, are completely their own implementation of the session. PHP (4,5) provides a session, the system by default will be saved with a cookie session_id
My previous project, users are using the Web in the intranet. In order to facilitate management, directly to the browser IP tied to a session, is to use the browser IP address instead of SessionID. There is no cookie in this scheme, but it is a session and should be defined as his absence from the session.
Each time a request is made to the server, the local browser will attach the cookie to the request message
Actually, it has nothing to do with the session, just the way the cookie works in the HTTP protocol. This cookie is written by the session_start () function, and we can write the cookie on our own, as long as it is written and does not expire, and the browser can send it.
PHP version--http session cookie principle and application