PHP - Cookies的工作 [英] PHP - Working of Cookies
问题描述
我在理解PHP中使用Cookie时遇到困难,
请考虑以下代码段
public function preExecute(){
setcookie(testCookie,Hello123,time()+ 31536000,/,WebServer :: getServerName());
echoBefore price of cookine in decommission ::。$ _ COOKIE [testCookie];
setcookie(testCookie,Hello456,time()+ 31536000,/,WebServer :: getServerName());
echoAfter price of cookine in decommission ::。$ _ COOKIE [testCookie];
}
我希望此代码的输出
After cookine在退役前的价值:: Hello123
Hello456
但我得到上述代码片段的输出是
退役后的烹饪:: Hello456
退役后的烹饪价值: Hello456
$ b
如果有人解释我的工作,我已经通过互联网上可用的资源,但仍然不清楚。
。
$ _ COOKIE
持有已收到的Cookie 在当前请求中。当您调用 setcookie
在响应中设置Cookie时,不会自动更新。您通过 setcookie
设置的Cookie只会出现在下一个请求中的 $ _ COOKIE
当cookie被发送回服务器。
所以你看到的是第二个cookie覆盖第一个,所以只有后面的值被发送回服务器。我想你已经刷新了几次页面,所以你看到的cookie。如果您清理Cookie并再次执行此操作,请先 尝试不会看到任何输出,因为 $ _ COOKIE
是空的并保持为空对于整个请求,无论你多久调用 setcookie
。
I am facing a difficulty in understanding the usage of cookies in PHP, Please consider the following code snippet
public function preExecute() {
setcookie("testCookie", "Hello123", time() + 31536000, "/", WebServer::getServerName());
echo "Before Value of cookine in decommission::".$_COOKIE["testCookie"];
setcookie("testCookie", "Hello456", time() + 31536000, "/", WebServer::getServerName());
echo "After Value of cookine in decommission::".$_COOKIE["testCookie"];
}
The output that i am expecting for this code
Before Value of cookine in decommission::Hello123
After Value of cookine in decommission::Hello456
But the output i am getting for the above code snippet is
Before Value of cookine in decommission::Hello456
After Value of cookine in decommission::Hello456
Will appreciate if someone explain me the working, i have gone through resources available in internet, but still i am not clear.
Thanks in advance.
$_COOKIE
holds the cookies that have been received in the current request. It is not automatically updated when you call setcookie
to set cookies in your response. The cookies you set via setcookie
will only appear in $_COOKIE
on the next request, when the cookies are sent back to the server.
So what you're seeing is that the second cookie overwrites the first, so only the later value is sent back to the server. I'll guess you have refreshed the page several times already, so you're seeing the cookie. If you clean your cookies and run this again, on the first try you won't see any output, because $_COOKIE
is empty and stays empty for the whole request, no matter how often you call setcookie
.
这篇关于PHP - Cookies的工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!