PHP重定向使用cookie和标头

时间:2011-01-26 18:11:40

标签: php cookies redirect header

我正在学习PHP并试图根据cookie的设置重新定位页面,所以下面是用于在第一页上设置cookie的代码

<?php
setcookie("test","logged in",time()+60,'/');
?>

现在在测试页面上我删除了cookie,但下面没有删除代码

<?php
setcookie("test", 0, time()-(60*60*24*7));

if(isset($_COOKIE['test']))
{
    echo "u had logged in";
}
else
header("Location: index.php");
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>

</body>
</html>

究竟是什么问题?

2 个答案:

答案 0 :(得分:3)

Cookie仅在页面传输到浏览器时设置,并且只有在作为HTTP请求的一部分发送到服务器时才会被读取。

因此:

  1. 如果您删除了Cookie,则在下一页加载之前它不会消失。

  2. 如果您设置了Cookie,则在下一页加载之前无法读取该值。

  3. 处理此问题的常用方法是设置/删除cookie,然后执行重定向。

答案 1 :(得分:0)

对Cookie所做的更改仅在刷新时对服务器可见。如果您重新加载测试页面,则不应看到“已登录”文本。

相关问题