PHP – setcookie() 不起作用

2021-12-21 00:00:00 cookies php

我有这个页面,它设置了一个 cookie,如果你选中一个复选框,它会回显一个字符串.字符串打印正确,但 cookie 从未设置,我不知道为什么.

I have this page that sets a cookie and echos out a string if you check a checkbox. The string prints correctly, but the cookie never gets set and I have no idea why.

<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
<label for="checkbox">Option 1:</label>
<input type="checkbox" name="checkbox" id="checkbox"><br>
<input type="submit" name="submit" value="Submit">
</form>
  <?php
if (isset($_POST['checkbox'])) {
  setcookie("cookie", "on", time()+3600*24);
  echo "You checked the checkbox and a cookie was set with a value of:<br>";
}
else {
  setcookie("cookie", "off", time()+3600*24);
  echo "You didn't check the checkbox and a cookie was set with a value of:<br>";
}
echo $_COOKIE['cookie'];
  ?>

有谁知道为什么上面的代码不起作用?

Does anyone know why the above code does not work?

推荐答案

PHP 超全局变量在脚本启动时填充,然后在脚本的整个生命周期内不再被 PHP 修改或触及.这意味着 $_COOKIE 表示在启动脚本的 http 请求中发送到服务器的 cookie.它不会显示您在脚本生命周期中添加/更改/删除的任何 cookie.这些更改只会显示在 NEXT 请求中.

PHP superglobals are populated at script start-up time, and then are NOT modified or touched by PHP again for the life of the script. That means $_COOKIE represents the cookies that were sent to the server in the http request that fired up the script. It will NOT show any cookies you've added/changed/deleted during the life of the script. Those changes will only show up on the NEXT request.

唯一的例外是 $_SESSION,它在您调用 session_start() 时填充.

The only exception to this is $_SESSION, which is populated when you call session_start().

如果您需要立即将这些值添加到 $_COOKIE 中,则必须手动添加它们,例如

If you need those values to be in $_COOKIE immediately, you'll have to add them manually, e.g.

setcookie('cookie', $value, ....);
$_COOKIE['cookie'] = $value;

相关文章