Home >Backend Development >PHP Tutorial >Dynamic web page technology PHP analysis of cookies and sessions_PHP tutorial
1. PHP COOKIE
Cookie is a mechanism that stores data on the remote browser side and uses it to track and identify users.
PHP sends cookies in the header information of the http protocol, so the setcookie() function must be called before other information is output to the browser, which is similar to the restriction on the header() function.
1.1 Set cookies:
You can use the setcookie() or setrawcookie() function to set cookies. It can also be set by sending http headers directly to the client.
1.1.1 Use the setcookie() function to set cookies:
bool setcookie ( string name [, string value [, int expire [, string path [, string domain [, bool secure [, bool httponly]]]]] )
name: cookie variable name
value: cookie variable value
expire: end of validity period,
path: valid directory ,
domain: valid domain name, unique top-level domain
secure: If the value is 1, the cookie can only be valid on https connections, if it is the default value 0, both http and https are available.
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 subdomains */
?>
Set multiple cookie variables: setcookie(var[a],value); use arrays to represent variables, But his subscript does not need 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 above for the setcookie function.
For example:
$value = something from somewhere;
header("Set-Cookie:name=$value");
1.2 Cookie reading:
Directly use php built-in super global variable $ _COOKIE can read the cookie on the browser side.
In the above example, the cookie "TestCookie" is set. Now let's read it:
print $_COOKIE[TestCookie];
Has COOKIE been output?!
1.3 To delete cookies
Just set the validity time to be less than the current time, and set the value to empty. For example:
setcookie("name","",time()-1);
Similar to using header().
1.4 FAQs:
1) There is an error message when using setcookie(). It may be because there is output or space before calling setcookie(). It may also be that your document is imported from other After the character set is converted, the document may have a BOM signature (that is, adding some hidden BOM characters to the file content). The solution is to prevent this situation from happening in your document. You can also use the ob_start() function. Handle it a bit.
2) $_COOKIE is affected by magic_quotes_gpc and may be automatically escaped
3) When using it, it is necessary to test whether the user supports cookies
2. PHP’s Session
session uses a cookie with an expiration time set to 0, and a unique identifier called session ID character (a long string of strings), some session files are synchronously generated on the server side (you can define the storage type of the session yourself), and are associated with the user machine. The web application stores data related to these sessions, and lets the data follow Users pass between pages.
Visitors to the website are assigned a unique identifier, a so-called session ID. It is either stored in a client-side cookie or passed via the URL.
Session support allows users to register any number of variables and reserve them for each request. When a visitor accesses the website, PHP checks whether a specific session ID was sent in the request, either automatically (if session.auto_start is set to 1) or when the user requests it (explicitly called by session_start() or implicitly by session_register()). If so, the previously saved environment is recreated.
2.1 Transmission of session ID
2.1.1 Transmission of session ID through cookie
Use session_start() to call the session. While generating the session file, the server generates the session ID hash value and the session with the default value of PHPSESSID. name, and sends the variable to the client (the default is) PHPSESSID (session name), the value is a 128-bit hash value. The server will interact with the client through this cookie.
The value of the session variable is PHP is internally serialized and stored in a text file on the server machine, and interacts with the client's coolie whose 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());
When jumping to a new page from this page and calling session_start(), PHP will check and The session data stored on the server side associated with the given ID, if not found, creates a new data set.
2.1.2 Transmit session ID through URL
This is only used when the user prohibits the use of cookies. Method, because browser cookies are already universal, for security reasons, this method does not need to be used.
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 session variable and assign value to session variable*/
$_SESSION[favcolor] = green;
$_SESSION[animal] = cat;
$_SESSION[time] = time();
// If the client uses cookies, you can directly pass the session to page2.php
echo
page 2;
// If the client disables cookies
echo
page 2 a>;
/*
By default under php5.2.1, the SID will only have a value when the cookie is written. If the cookie corresponding to the session
already exists, then the SID will be (undefined )Empty
*/
?>
// page2.php
session_start();
print $_SESSION[animal]; // Print out a single session
var_dump($_SESSION); // Print out the session value passed by page1.php
?>
2.3 Use the session function to control the page cache.
In many cases, we need to make sure we Whether the webpage is cached on the client, or the cache validity time needs to be set. For example, there are some sensitive contents on our webpage and you need to log in to view it. If it is cached locally, you can directly open the local cache and browse to the webpage without logging in. .
Use session_cache_limiter(private); you can 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.
To control the client cache time, use session_cache_expire(int); unit (s). It must also be called before session_start().
This is only to control the cache when using session Method, we can also control the cache of the control page in header().
2.4 Deleting session
requires three steps.
session_destroy(); : Delete the server-side session file, use
setcookie(session_name(),,time()-3600); // Step 2: Delete the actual session:
$_SESSION = array(); Three steps: Delete the $_SESSION global variable array
?>
2.5 Use of session in PHP large-scale web applications
For sites with a large number of visits, the default session storage method is not suitable. Currently The best way is to use the database to access the session. At this time, the function bool session_set_save_handler (callback open, callback close, callback read, callback write, callback destroy, callback gc) provides us with a solution to this problem.
The The six functions used by the function are as follows:
1. bool open() is used to open the session storage mechanism,
2. bool close() closes the session storage operation.
3. mixde read() from storage Use this function when loading session data
4. bool write() writes all data for the given session ID to 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 an example, see the session_set_save_handler() function in the PHP manual.
If you use a class to process it, use
session_set_save_handler(
array(className,