Dynamic web technology PHP analysis on cookies and sessions _ PHP Tutorial

Source: Internet
Author: User
Tags http cookie php session php print
Dynamic web page technology PHP analysis on cookies and sessions. 1. COOKIEcookie of PHP is a mechanism for storing data on a remote browser to track and identify users. PHP sends cookies in the http header, so the setcookie () function must be 1. 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.
1.1 Set cookie:
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.
1.1.1 Use the setcookie () function to set the cookie:
Bool setcookie (string name [, string value [, int expire [, string path [, string domain [, bool secure [, bool httponly])
Name: cookie variable name
Value: The value of the cookie variable.
Expire: the end time of the validity period,
Path: valid directory,
Domain: valid domain name, unique in top-level domain
Secure: if the value is 1, the cookie can only be valid for https connections. if the default value is 0, both http and https can be used.
Example:
$ 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 the variable, but its subscript does not use quotation marks. in this way, you can use $ _ COOKIE ['var'] ['A'] to read the COOKIE variable.
1.1.2. use header () to set the cookie;
Header ("Set-Cookie: name = $ value [; path = $ path [; domain = xxx.com [;...]");
The following parameters are the same as those listed in the setcookie function above.
For example:
$ Value = something from somewhere;
Header ("Set-Cookie: name = $ value ");
1.2 Cookie reading:
Directly use php's built-in Super global variable $ _ COOKIE to read the cookie on the browser.
The cookie "TestCookie" is set in the preceding example. now we can read:
Print $ _ COOKIE [TestCookie];
Is the COOKIE output ?!
1.3 Delete a cookie
Set the effective time to less than the current time, and set the value to null. for example:
Setcookie ("name", "", time ()-1 );
Similar to header.
1.4 Troubleshooting:
1) an error message is prompted when setcookie () is used, probably because there is an output or space before setcookie () is called. it is also possible that your document is converted from other character sets. 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 in your document. you can also use the ob_start () function to handle this problem.
2) $ _ COOKIE is affected by magic_quotes_gpc and may be automatically escaped
3) it is necessary to test whether the user supports cookies.

1.5 cookie working mechanism:
Some learners are impulsive and have no idea about the principle, so I put it behind me.
A) the server sends an http Set-Cookie header in response and sets a cookie in the client (multiple cookies require 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 setcookie (TestCookie, something from somewhere. that is, the result of using header (Set-Cookie: TestCookie = something from somewhere; path =.

2. 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 (you can define the session storage type by yourself) and associate them with the user machine. web applications store data related to these sessions, and transmit data between pages as users.
Visitors to the website will be assigned a unique identifier, the so-called session ID. It is either a cookie stored on the client or transmitted through a URL.
Session support allows users to register any number of variables and keep them for use by each request. When visitors visit the website, PHP will automatically (if session. auto_start is set to 1) or when a user request (explicitly called by session_start () or secretly called by session_register () checks whether a specific session ID is sent in the request. If yes, the previously saved environment is rebuilt.
2.1 Transfer of sessionID
2.1.1 send sessin 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 will use 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.
2.1.2 send 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.
2.2 Basic session usage example
// 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
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
*/
?>
// Page2.php
Session_start ();
Print $ _ SESSION [animal]; // print a single session
Var_dump ($ _ SESSION); // Print the session value passed by page1.php.
?>
2.3 use the session function to control page cache.
In many cases, we need to determine whether our webpage is cached on the client or set the cache validity period. for example, we need to log on to the webpage to view some sensitive content, if the cache is cached locally, you can directly open the local cache to browse the webpage without logging on.
Use session_cache_limiter (private); to control the page client cache, which must be called before session_start.
For more parameters, see http://blog.chinaunix.net/u/27731/showart.php? Client cache control with id = 258087.
Use session_cache_expire (int) to control the client cache time; unit (s). it must also be called before session_start.
This is only a method for controlling the cache when session is used. we can also control the page cache in header.
2.4 delete a session
Three steps are required.
Session_destroy (); // Step 1: delete the session file on the server.
Setcookie (session_name (), time ()-3600); // Step 2: delete the actual session:
$ _ SESSION = array (); // Step 3: delete the $ _ SESSION global variable array
?>
2.5 session usage in PHP large-scale web applications
The default session storage method is not suitable for websites with large traffic volumes. Currently, the optimal method is to access sessions using databases. at this time, the function bool session_set_save_handler (callback open, callback close, callback read, callback write, callback destroy, callback gc) is the solution to solve this problem.
The function uses the following six functions:
1. bool open () is used to open the session storage mechanism,
2. bool close () closes the session storage operation.
3. this function is used when mixde read () is installed in session data from the storage.
4. bool write () writes all data of the given session ID to the storage.
5. bool destroy () destroys the data associated with the specified session ID
6. bool gc () garbage collection of data in the storage system
For example, see the session_set_save_handler () function in the php Manual.
If the class is used for processing, use
Session_set_save_handler (
Array (className,

COOKIE cookies for http://www.bkjia.com/PHPjc/486616.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/486616.htmlTechArticle1. PHP are a mechanism for storing data on a remote browser to track and identify users. PHP sends a cookie in the http header. Therefore, the setcookie () function is required...

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.