我是初学者使用php cookies,我正在尝试使用cookie制作一个简单的登录和注销表单。一切都很好但是当我按下注销链接时我无法注销。要注销我必须从浏览器中删除cookie。
log_in page
<?php
session_start();
if (isset($_COOKIE["Email"])){
header("location: home.php");
}
?>
<form method="post" action="log_in.php">
<font size="6">Sign In</font>
Email Address: </b></font><input type="text" name="Email" id="email" />
password: <input type="password" name="password" id="password" />
<input type="checkbox" name="rememberMe" value="1" id="check"/> Remember Me
<input type="submit" name="Login" id="sign" value="sign in" >
<?php
include 'db.php';
if(isset($_POST['Login'])){
$user_email = $_POST['Email'];
$password = $_POST['password'];
$check_user = "SELECT * FROM user where user_email = '$user_email' AND user_pass = '$password'";
$run = mysql_query($check_user );
if (mysql_num_rows($run) > 0){
$_SESSION['Email']= $user_email;
$_SESSION['start'] = time();
if(isset($_POST['rememberMe'])){
$expire=time()+120;
setcookie("Email", "Email", $expire);
}
else{
$expire=time()+30;
setcookie("Email", "Email", $expire);
}
echo "<script>window.open('home.php','_self')</script>";
}
else {
echo "<script>alert('email or password incorrect!')</script>";
}}
?>
主页
<?php
if (isset($_COOKIE["Email"])){
echo "Welcome " . $_COOKIE["Email"] . "!<br>";
echo '<a href="logoutForm.php">logout</a>';
}
else{
$now = time(); // Checking the time now when home page starts.
if ($now > $expire) {
session_destroy();
header("location: log_in.php");
}}
退出页面
<?php
session_start();
unset($_SESSION['Email']);
session_destroy();
header("Location: log_in.php");
if(isset($_SESSION['Email'])):
setcookie($_SESSION['Email'],'',time()-7000000,'/');
endif;
?>
答案 0 :(得分:5)
您的主页(代码)中没有session_start();
最少没有您发布的内容;使用session_destroy()
时需要它;它本身不起作用。
放手一搏:
对于$expire
代码, 旁注: home page
未定义,因此您需要使用与您使用的相同或类似的方法其他页面。
<?php
if (isset($_COOKIE["Email"])){
echo "Welcome " . $_COOKIE["Email"] . "!<br>";
echo '<a href="logoutForm.php">logout</a>';
}
else{
$now = time(); // Checking the time now when home page starts.
if ($now > $expire) { // $expire is undefined
session_start(); // <= required
session_destroy(); // <= does not work on its own
header("location: log_in.php");
}
}
答案 1 :(得分:0)
如果你想要完全破坏会话,你可以使用session_destroy()
<?php
session_start();
session_destroy();
?>
或者,如果您只想取消设置电子邮件,可以使用
<?php
session_start();
if(isset($_SESSION['Email']))
unset($_SESSION['Email']);
?>