问题
I'm not sure why, but the following doesn't seem to work as expected:
<?php
setcookie('my_cookie', $_GET['v'], time() + (86400 * 7));
echo $_COOKIE['my_cookie'];
?>
If you put this in a file on a PHP web server and call it with a query of yourdomain.com/index.php?v=value
. The value only gets printed to the page on the 2nd request. Why not on the 1st?
回答1:
The $_COOKIE array represents only those cookies that came in the request from the client. setcookie() adds an HTTP header asking the client to send the cookie during subsequent requests.
Typically, you shouldn't want it to appear like more cookies were in the request than actually were. Rather, you should generally process cookies early in the script, maintain state elsewhere, and set or reset cookies late in the script.
回答2:
setcookie("my_cookie", "value")
creates a HTTP header, Set-Cookie: my_cookie=value
, in the response to the browser. The browser stores this cookie.
The next time the same client calls the server, it will include the cookie in the request as a header, Cookie: my_cookie=value
, and php makes it available as $_COOKIE['my_cookie']
.
You can also check this with print_r($_COOKIE)
or print_r($_REQUEST)
for the raw headers.
来源:https://stackoverflow.com/questions/18033549/how-to-write-print-a-php-cookie-in-the-same-request