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 = 'something from somewhere'; //设置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 variables_order includes "C", 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['cookie'])) { foreach ($_COOKIE['cookie'] as $name => $value) { $name = htmlspecialchars($name); $value = htmlspecialchars($value); echo "$name : $value <br />\n"; } } ?>
According to register_globals settings, 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); ?>