PHP version--http session cookie principle and application

Source: Internet
Author: User
Tags http cookie php print setcookie
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

    1. $value = ' Something from somewhere ' ;
    2. Setcookie ("TestCookie", $value); / * Simple cookie settings * /
    3. Setcookie ("TestCookie", $value, Time () +3600); / * Valid for 1 hours * *
    4. Setcookie ("TestCookie", $value, Time () +3600, "/~rasmus/" ,
    5. ". example.com" , 1); / * Valid directory/~rasmus, valid domain name example.com and all sub-domains * /

Set multiple cookie variables: Setcookie (' var[a] ', ' value '), use an array to represent the variable, 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

    1. $value = ' Something from somewhere ' ;
    2. 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

    1. 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

    1. 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.
= ">xxx, you can also pass the session value via post."

--------------------------------------------------------------------------------------------------------------- ---------------

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

  1. //page1.php
  2. Session_Start ();
  3. Echo ' Welcome to page #1 ';
  4. / * Create session variable and assign value to session variable * /
  5. $_session [' Favcolor '] = ' Green ' ;
  6. $_session [' animal '] = ' Cat ' ;
  7. $_session [' time '] = time ();
  8. //If the client uses cookies, it can pass the session directly to page2.php
  9. Echo '
    Page 2 ';
  10. //If the client disables cookies
  11. Echo '
    . Sid. ' ">page 2 ';
  12. /*
  13. By default php5.2.1, the SID will have a value only if the cookie is written, if the session
  14. the corresponding cookie already exists, then the SID will be (undefined) null
  15. */

PHP code

    1. //page2.php
    2. Session_Start ();
    3. Print $_session[' animal ']; //Print out a single session
    4. Var_dump ($_session); //Print out the session value passed by page1.php.

Delete session:

eg

PHP code

    1. Session_destroy (); ///First step: Delete the server-side session file, which uses
    2. Setcookie (Session_name (),", Time () -3600); ///Step Two: Delete the actual session:
    3. $_session = Array (); //Step three: Delete $_session global variable array
    4. ?>

--------------------------------------------------------------------------------------------------------------- ---------------

A simple example:

PHP Code:

PHP code

    1. Session_Start ();
    2. if (Isset ($_session[' test_sess ')]) {
    3. $_session [' test_sess ']++;
    4. }Else{
    5. $_session [' test_sess '] = 0;
    6. }
    7. 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:

as long as the session is used, the session is sent to the client browser via a cookie
Actually, the session is completely an abstract concept, the session really does, is in addition to the HTTP provided by the GET and post provided parameters, for a user (may be a browser, or a computer, or even an IP), can save additional information. 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.
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 previously stored data. 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 provided by the session function, you 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 use a cookie to save session_id
My previous project, the user in the intranet using the Web. 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.

The above describes the PHP version--http session cookie principle and application, including the aspects of the content, I hope that the PHP tutorial interested in a friend helpful.

  • 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.