在setcookie()之后立即访问$ _COOKIE [英] Accessing $_COOKIE immediately after setcookie()

查看:103
本文介绍了在setcookie()之后立即访问$ _COOKIE的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在调用 setcookie()后立即访问cookie的值(使用 $ _ COOKIE 函数在PHP。当我这样做, $ _ 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆