问题描述
我试图在 PHP 中调用 setcookie()
函数后立即访问 cookie 的值(使用 $_COOKIE
).当我这样做时,没有设置 $_COOKIE['uname']
.为什么?
I'm trying to access a cookie's value (using $_COOKIE
) immediately after calling the setcookie()
function in PHP. When I do so, $_COOKIE['uname']
isn't set. Why?
但是请注意,$_COOKIE['uname']
在脚本下次执行时按预期设置,例如在页面刷新后.
Note, however, that $_COOKIE['uname']
is set as expected upon the next execution of the script, such as after a page refresh.
setcookie('uname', $uname, time() + 60 * 30);
echo "Cookie value: " . $_COOKIE['uname'];
推荐答案
$_COOKIE
在页面加载时设置,这是由于网络的无状态特性.如果您想立即访问,您可以自己设置 $_COOKIE['uname']
或使用中间变量.
$_COOKIE
is set when the page loads, due to the stateless nature of the web. If you want immediate access, you can set $_COOKIE['uname']
yourself or use an intermediate variable.
例如:
if (isset($_COOKIE['uname'])) {
// get data from cookie for local use
$uname = $_COOKIE['uname'];
}
else {
// set cookie, local $uname already set
setcookie('uname', $uname, time() + 1800);
}
这篇关于在 setcookie() 之后立即访问 $_COOKIE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!