为什么会话结束也会破坏cookie?

时间:2015-08-18 07:26:55

标签: php session cookies

我正在尝试模拟登录注销(我是初学者),我必须使用会话和cookie。

因此,如果我在登录时选中“记住我”选项,我会使用持续20秒的cookie并记住用户名和密码。

并且还使用了一个会话。

但是,当我尝试注销时,如果我在前20秒内完成,Mozzila会给我一个错误。 为什么这样?

这是登录文件

<?php
session_start();
$user="username";
$pass="password";

//verify if there is a cookie, and if so, log in from the cookie
if(isset($_COOKIE['u']) && isset($_COOKIE['p']) && $_COOKIE['u']==$user && $_COOKIE['p']==$pass){
	header("location: Index.php");
	exit;
	}

if(isset($_POST['sub']))
	if(empty($_POST['name'])) echo "Please write username";
		elseif(empty($_POST['pass'])) echo "Please write password";
		else
			if($_POST['name']==$user && $_POST['pass']==$pass){
		
				if($_POST['rem']=="on"){
					setcookie("u", $_POST['name'],time()+10);
					setcookie("p", $_POST['pass'],time()+10);
					}
					
				$_SESSION['logged']="yes";
				$_SESSION['name']=$_POST['name'];
				header("location: Index.php");
				exit;
				}
				else echo "Incorrect data";


?>




<html>
<head>
	<title> Login </title>
</head>
<body>
<form method="post">
<input type="text" name="name" placeholder="username" /><br />
<input type="password" name="pass" placeholder="password"/><br />
<input type="checkbox" name="rem" />Remember me<br />
<input type="submit" name="sub" value="Log in" /> 
</form>
</html>

这是退出:

<?php
session_start();
$_SESSION=array();
session_destroy();
header("location: Login.php");
exit;


?>

<?php
session_start();

//verificam daca nu a ajuns fortat pe pagina, si ca mai intai s-a logat
if(!isset($_SESSION['logged']) || $_SESSION['logged']!="yes"){
	header("location: Login.php");
	exit; 
	}

?>


<html>
<head>
	<title> Index </title>
</head>
<body>
	Welcome, <?php echo $_SESSION['name'];?>!
	<br /><br /><br />
	<a href="Logout.php"> Log out! </a>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

<强> Logout.php:

检查此注销脚本。在这里,我将使cookie过期以停止重定向循环。保持所有脚本不变。只更新logout.php,如下所示:

<?php

session_start();
$_SESSION=array();
session_destroy();
setcookie("u", $_POST['name'],time()-10);
setcookie("p", $_POST['pass'],time()-10);
header("location: Login.php");
exit;


?>