我已经在 php 中编写了登录和注销脚本。我可以登录但注销不起作用。有人请指出错误。我完全迷路了。这是完整的代码。
1.登录php代码:
<?php
session_start();
require_once('login/connectvars.php');
$msg = "";
if(!isset($_SESSION['username']) && isset($_COOKIE['username']))
{
$_SESSION['username'] = $_COOKIE['username'];
}
if(isset($_POST['submit']))
{
$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']));
if(!empty($username) && !empty($password))
{
$query = "SELECT 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['username'] = $row['username'];
setcookie('username',$row['username'],time()+(60*6));
$msg = 'success';
}
else
{
$msg = 'enter correct values..';
}
}
else
{
$msg = 'Enter all fields..';
}
}
?>
2.我在 HTML 中用于检查会话的代码。
<div id="login_form">
<h2>
<?php echo $msg; ?>
</h2>
<?php
if(isset($_SESSION['username']))
{
echo 'nothing<br />';
echo '<a href="login/logout.php">log out'.$_SESSION['username'].'</a><br />';
}
else
{
?>
<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>
<?php
}
?>
<!-- login form -->
</div>
3.注销脚本
<?php
session_start();
if(isset($_SESSION['username']))
{
$_SESSION = array();
if(isset($_COOKIE[session_name()]))
{
setcookie(session_name(),'',time() - 3600);
}
session_destroy();
}
setcookie('username','',time() - 3600);
echo 'redirecting you...please wait..';
header("Refresh: 3;url=http://localhost/");
?>