Cookies in php ---------------------------------------------------------------------------
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 variables, but its subscript is not enclosed in 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 ['testcooker'];
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.