清除我的cookie以便我可以对它进行新的测试后,我尝试制作一个简单的表格来设置cookie。然而,在输入文本表单并按下提交按钮后,它似乎设置了cookie,但是在您再次按下提交之前无法识别它(表单中没有任何内容)。听起来很奇怪,但你可以亲自尝试一下。我缩小了代码以使其变得简单。
<?php
if(isset($_GET['email'])){
$email = $_GET['email'];
$time = time() + 60;
setcookie('email',$email,$time);
$cookie = $_COOKIE['email'];
echo 'Cookie successfully created: '.$cookie.'<br><br>';
}
if(isset($_COOKIE['email'])){
echo 'Hello there!';
}else if(!isset($_COOKIE['email'])){
echo '<form action="test.php" method="GET">
<p>Please provide your email address</p>
<input type="text" name="email" size="25" /><input type="submit" value="Submit" />
</form>';
}
?>
我缺少一些简单的事情。有线索吗?
答案 0 :(得分:1)
当浏览器第一次加载页面时,Cookie才会写入浏览器。所以第二次检查只适用于下一页加载。
处理此问题的最佳方法是:
<?php
if(isset($_GET['email'])){
$email = $_GET['email'];
$time = time() + 60;
setcookie('email',$email,$time);
$cookie = $_COOKIE['email'];
echo 'Cookie successfully created: '.$cookie.'<br><br>';
}
if(isset($_COOKIE['email']) || isset($_GET['email'])){
echo 'Hello there!';
}else if(!isset($_COOKIE['email'])){
echo '<form action="test.php" method="GET">
<p>Please provide your email address</p>
<input type="text" name="email" size="25" /><input type="submit" value="Submit" />
</form>';
}
?>
检查首先设置cookie的_GET变量将允许您的脚本处理第一次和后续页面加载。