How to write & print a PHP cookie in the same request?

僤鯓⒐⒋嵵緔 提交于 2021-02-08 08:25:50

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!