1.第一次为空
2.第二次输出 test
解释:cookies是保存在客户端的,服务器要想获得cookie必须是客户端通过http的header传递给服务器。
第一次:首先设置一个cookie值,然后读取cookie值(由于第一次客户端没有传递cookie给服务器),没有cookie值
第二次:cookie值传递给了服务器,就读出来了
在面试官的指点后,我才想起来了之前有项目的bug与这个有关,但是换个方法避开了。
碰巧这几天看php手册看到了setcookie中有这样一段代码:
<?php
// set the cookies
setcookie("cookie[three]", "cookiethree");
setcookie("cookie[two]", "cookietwo");
setcookie("cookie[one]", "cookieone");
// after the page reloads, print them out
if (isset($_COOKIE['cookie'])) {
foreach ($_COOKIE['cookie'] as $name => $value) {
$name = htmlspecialchars($name);
$value = htmlspecialchars($value);
echo "$name : $value <br />\n";
}
}
?>
亮点
// after the page reloads, print them out