我有这个页面,它设置了一个 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;
这篇关于PHP – setcookie() 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
在 SELECT(MYSQL/PHP) 中加入 2 个表Joining 2 tables in SELECT(MYSQL/PHP)(在 SELECT(MYSQL/PHP) 中加入 2 个表)
如何使<option selected=“selected">由How to make lt;option selected=quot;selectedquot;gt; set by MySQL and PHP?(如何使lt;option selected=“selectedgt;由 MySQL 和 PHP 设置?)
使用 PHP 中的数组自动填充选择框Auto populate a select box using an array in PHP(使用 PHP 中的数组自动填充选择框)
PHP SQL SELECT where like search item with multiple wordsPHP SQL SELECT where like search item with multiple words(PHP SQL SELECT where like search item with multiple words)
json_encode 从 MSSQL-SELECT 产生 JSON_ERROR_UTF8json_encode produce JSON_ERROR_UTF8 from MSSQL-SELECT(json_encode 从 MSSQL-SELECT 产生 JSON_ERROR_UTF8)
MySQL ORDER BY rand(),名称 ASCMySQL ORDER BY rand(), name ASC(MySQL ORDER BY rand(),名称 ASC)