0
我已經寫了一個使用會話和cookie的php登錄腳本。 我知道會話在關閉瀏覽器後即會過期,但Cookie會一直存在,直到達到其到期時間。在我的腳本中,我創建了一個COOKIE來存儲登錄用戶的「用戶名」。 登錄後,如果我關閉瀏覽器並重新打開它..我必須仍然保持登錄,因爲cookie.And當我點擊註銷我必須註銷。 但我的腳本無法正常工作,因爲在點擊「註銷」按鈕鏈接後,我的腳本沒有註銷。cookie不工作在PHP登錄
這裏是PHP代碼,我寫道:
<?php
session_start();
require_once('login/connectvars.php');
if(!isset($_SESSION['username']) && isset($_COOKIE['username']))
{
$_SESSION['username'] = $_COOKIE['username'];
}
if(isset($_POST['submit']))
{
if(!empty($_POST['username']) && !empty($_POST['password']))
{
$dbc = mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME);
$username = mysqli_real_escape_string($dbc,trim($_POST['username']));
$password = mysqli_real_escape_string($dbc,trim($_POST['password']));
$query = "SELECT user_id,username FROM users_dns WHERE username = '$username' AND password = SHA('$password')";
$data = mysqli_query($dbc,$query) or die(mysqli_error($dbc));
if(mysqli_num_rows($data) == 1)
{
$row = mysqli_fetch_array($data);
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['username'] = $row['username'];
setcookie('username',$row['username'],time() + (60 * 60));
echo 'success';
mysqli_close($dbc);
}
else
{
echo 'enter correct username and password';
}
}
else
{
echo 'no empty fields please..';
}
}
?>
這裏就是我使用的HTML代碼:
<?php
if(isset($_SESSION['username']))
{
echo 'logged in as'.$_SESSION['username'];
echo '<a href="login/logout.php">log out ('.$_SESSION['username'].')</a><br />';
echo $_SESSION['username'];
}
else
{
?>
<div id="login_form">
<!--<span class="error"><?php echo $error_msg; ?></span>-->
<form id="login" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<table>
<tr>
<th>Username:</th>
<th>Password:</th>
</tr>
<tr>
<td><input type="text" name="username" /></td>
<td><input type="password" name="password" /></td>
</tr>
<tr>
<td><input type="submit" name="submit" value="Log In" class="submit" /></td>
<td><a href="login/signup.php"><input type="button" class="submit" value="Sign Up" /></a></td>
</tr>
</table>
</form>
</div>
<?php
}
?>
這裏是我的註銷腳本
<?php
session_start();
if(isset($_SESSION['username']))
{
$_SESSION = array();
if(isset($_COOKIE['session_name()']))
{
setcookie('username','',time() - 3600);
}
session_destroy();
}
setcookie('user_id','',time() - 3600);
setcookie('username','',time() - 3600);
echo 'redirecting you...please wait..';
header("Refresh: 3;url=http://localhost/");
?>
你在哪裏使用cookie來檢查登錄? –
oh..right ... 我在開頭添加了代碼..但是現在它沒有註銷。 – Pradeep