問題描述
我有這個頁面,它設置了一個 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 請求中發(fā)送到服務器的 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模板網!