【发布时间】:2013-05-03 13:41:28
【问题描述】:
这是一个代码示例:
if (!empty($_GET['supahCookie']))
{
setcookie("myCookie", $_GET['supahCookie'], time()+3600*24*31);
}
$foo = empty($_COOKIE['myCookie'])?'Empty! :(':$_COOKIE['myCookie'];
echo $foo;
输出如下;
空! :(
首先,setcookie() 似乎是异步执行的,但如果您稍微考虑一下setcookie() 只需设置一个 cookie 标头,它就不会。 (小服务器浏览器对话)
问题是我需要立即访问新创建的 cookie。我该怎么做?
我想出的唯一方法就是这个:
if (!empty($_GET['supahCookie']))
{
setcookie("myCookie", $_GET['supahCookie'], time()+3600*24*31);
unset($_GET['search_type']); // to avoind redirect loop
header('Location: ./?'.http_build_query($_GET));
}
嗯..还有一个,有点乱:
$foo = empty($_GET['supahCookie'])?(empty($_COOKIE['myCookie'])?'Empty! :(':$_COOKIE['myCookie']):$_GET['supahCookie'];
我是不是又在这里发明了一个轮子?
还有其他更优雅的解决方案吗?
【问题讨论】:
-
setcookie('myCookie', $_GET['supahCookie'], time()+3600*24*31);$_COOKIE['myCookie']=$_GET['supahCookie'];