我遇到了这个问题,当我使用有效数据登录时,页面刚刚刷新(我假设 protectedstuff.php 中的 if 语句失败)。当我使用不推荐使用的方法注册会话并检查它是否存在时,它起作用了if(!session_is_registered(myusername))
。
哦,我还可以看到创建了一个 cookie “PHPSESSID”。
我究竟做错了什么?
登录.php ->
<?php
if($_POST){
$errorLogin="Wrong Username or Password";
$link = mysqli_connect('localhost', 'root', '', 'mydb')
or die('Could not connect: ' . mysqli_error($link));
// username and password sent from form
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];
$sql_query="SELECT * FROM users WHERE username='$myusername' and password='$mypassword';";
$result = mysqli_query($link, $sql_query) or die('query failed'. mysqli_error($link));
$row = mysqli_fetch_assoc($result);
$dbUserName= $row['username'];
$dbPassword= $row['password'];
// Mysql_num_row is counting table row
// If result matched $myusername and $mypassword,
if($myusername==$dbUserName && $mypassword==$dbPassword){
// Register $myusername, and redirect to file "login_success.php"
//session_register("myusername"); <- deprecated
$_SESSION['myusername']=$myusername;
header("location:protectedstuff.php");
}else {
echo $errorLogin;
}
}
?>
<table width="300" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<form name="form1" method="post">
<td>
<table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
<tr>
<td colspan="3"><strong>Login </strong></td>
</tr>
<tr>
<td width="78">Username</td>
<td width="6">:</td>
<td width="294"><input name="myusername" type="text" id="myusername"></td>
</tr>
<tr>
<td>Password</td>
<td>:</td>
<td><input name="mypassword" type="text" id="mypassword"></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td><input type="submit" name="Submit" value="Login"></td>
</tr>
</table>
</td>
</form>
</tr>
</table>
用户名和密码已经在数据库中。
这是我的 protectedstuff.php
<?php
session_start();
if(!isset($_SESSION['myusername']))
{
header("location:login.php");
}
else{
?>
<html>
<body>
Login Successful
</body>
</html>
<?php
}
?>
谢谢!