Home >Backend Development >PHP Tutorial >PHP Features Session Mechanism 1—Use of Cookies

PHP Features Session Mechanism 1—Use of Cookies

黄舟
黄舟Original
2017-02-04 09:38:341342browse

PHP transparently supports HTTP cookies. A cookie is a mechanism that stores data on a remote browser to track and identify users. Cookies can be set using the setcookie() or setrawcookie() functions. Cookies are part of the HTTP headers, so the setcookie() function must be called before other information is output to the browser, similar to the restrictions on the header() function. Output buffering functions can be used to delay the output of a script until all cookies or other HTTP headers have been set as required.
Example #1 setcookie() usage example

<?php  
$value = &#39;something from somewhere&#39;;  
//设置Cookie  
setcookie("TestCookie", $value);  
setcookie("TestCookie", $value, time()+3600); /* expire in 1 hour */  
setcookie("TestCookie", $value, time()+3600, "/~rasmus/", "example.com", 1);  
  
//删除Cookie  
setcookie ("TestCookie", "", time() - 3600);  
setcookie ("TestCookie", "", time() - 3600, "/~rasmus/", "example.com", 1);  
?>

If "C" is included in variables_order, any cookie sent from the client will be automatically included in the $_COOKIE automatic global array . If you want to set multiple values ​​for a cookie variable, you need to add the [] symbol after the cookie name.

<?php  
// set the cookies  
setcookie("cookie[three]", "cookiethree");  
setcookie("cookie[two]", "cookietwo");  
setcookie("cookie[one]", "cookieone");  
  
// after the page reloads, print them out  
if (isset($_COOKIE[&#39;cookie&#39;])) {  
    foreach ($_COOKIE[&#39;cookie&#39;] as $name => $value) {  
        $name = htmlspecialchars($name);  
        $value = htmlspecialchars($value);  
        echo "$name : $value <br />\n";  
    }  
}  
?>

According to the setting of register_globals, ordinary PHP variables can be created from cookies. However, relying on this feature is not recommended as this option is usually turned off for security reasons. In earlier versions of PHP, when the track_vars configuration option was turned on (this option was always turned on since PHP 4.0.3), $HTTP_COOKIE_VARS was also set.

<?php  
// Print an individual cookie  
echo $_COOKIE["TestCookie"];  
echo $HTTP_COOKIE_VARS["TestCookie"];  
  
// Another way to debug/test is to view all cookies  
print_r($_COOKIE);  
?>

The above is the content of session mechanism 1 of PHP characteristics - the use of cookies. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn