PHP Cookie未设置

时间:2017-03-23 21:29:39

标签: php

直到过去12个小时左右,我一直在撞墙,但我发现什么都不对。我想设置cookie但不能。现在变得厌倦了。

<!DOCTYPE html>
<?php
$cookie_name = "mysiterandomuser";
$cookie_value = "justanotheruser";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
?>

<html>
<body>

<?php
if(!isset($_COOKIE[$cookie_name])) {
     echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
     echo "Cookie '" . $cookie_name . "' is set!<br>";
     echo "Value is: " . $_COOKIE[$cookie_name];
}
?>

<p><strong>Note:</strong> You might have to reload the page to see the new value of the cookie.</p>

</body>
</html>

2 个答案:

答案 0 :(得分:4)

在已发送标题/内容后,您无法设置Cookie。您需要先设置cookie。

<?php
$cookie_name = "mysiterandomuser";
$cookie_value = "justanotheruser";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
?>
<!DOCTYPE html>
<html>
<body>

<?php
if(!isset($_COOKIE[$cookie_name])) {
     echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
     echo "Cookie '" . $cookie_name . "' is set!<br>";
     echo "Value is: " . $_COOKIE[$cookie_name];
}
?>

<p><strong>Note:</strong> You might have to reload the page to see the new value of the cookie.</p>

</body>
</html>

答案 1 :(得分:1)

根据docs on PHP.net ...

  

在下次加载页面之前,Cookie才会显示   cookie应该是可见的。测试cookie是否成功   设置,检查cookie之前的下一个加载页面上的cookie   到期。

改变这个......

<?php
$cookie_name = "mysiterandomuser";
$cookie_value = "justanotheruser";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
?>

To This ...

<?php
if(!isset($_COOKIE[$cookie_name])) {
$cookie_name = "mysiterandomuser";
$cookie_value = "justanotheruser";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
}
?>

原因是您要在每个页面视图上设置cookie。

请原谅我,但是你的浏览器是否启用了cookie?

相关问题