PHP无法从同一页面读取Cookie

时间:2016-08-11 12:11:05

标签: php html firefox cookies

嘿伙计们我创建了一个简单的PHP页面来设置一个cookie,并在重新加载后检查cookie是否存在并回显其内容。

设置cookie有效。重新加载工程。显示cookie有效。 但是:如果我离开页面(转到另一个网址等)并再次返回,该页面无法读取之前设置的cookie,尽管cookie尚未过期且firefox表示它仍然存在。

php文件的代码:

<!DOCTYPE html>

<html>
<title>Authentication cookie</title>
<body>

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">

Authentication code: <input type="text" name="authcode" value="<?php echo $_GET["authcode"]; ?>">
<input type="submit" name="submit" value="Submit">
</form><br>



<?php
$cookie_name = "authpi";
$cookie_value = $_POST["authcode"];
setcookie($cookie_name, $cookie_value, time() + (10 * 365 * 24 * 60 * 60), '/', '10.0.0.2'); // 86400 = 1 day

 ?>


<?php
if(!isset($_COOKIE["authpi"])) {
     echo "Authentication Cookie named '" . $cookie_name . "' is not set!";
        #header("Location: http://www.google.at/");
} else {
     echo "Authentication Cookie '" . $cookie_name . "' is set!<br>";
     echo "Your authentication code is: " . $_COOKIE[$cookie_name];
}
?>

 <p><strong>Note:</strong> After setting the Cookie reload the page to make sure it works!</p>
 </body>
</html>

感谢您的回答!

编辑:试图更好地解释我的问题。

1 个答案:

答案 0 :(得分:0)

设置后加载页面时设置

$_COOKIE如果您想立即访问,可以直接设置$_COOKIE['variable']

所以这样做

setcookie($cookie_name, $cookie_value, time() + (10 * 365 * 24 * 60 * 60), '/', '10.0.0.2'); // 86400 = 1 day
if(!isset($_COOKIE["authpi"]){
$_COOKIE[authpi] = $cookie_value;}
相关问题