用户登录没有';t重定向到index.php


User login doesn't redirect to index.php

我尝试使用会话进行php用户登录。我有3个文件。main_login.php、checklogin.php和index.php。注册用户名和密码后,它应该会将我引导到index.php文件,但它没有这样做。

main_login.php代码:

<html>
<body>
<table width="300" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<form name="form1" method="post" action="checklogin.php">
<td>
<table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
<tr>
<td colspan="3"><strong>Member 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="password" id="mypassword"></td>
</tr>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td><input type="submit" name="Submit" value="Login"></td>
</tr>
</table>
</td>
</form>
</tr>
</table>
</body>
</html>

checklogin.php代码:

    <?php
session_start()
include('connection.php');
if(!$conn)
{
  die('Could not connect: ' . mysql_error());
}
$tbl_name="user"; // Table name 

// username and password sent from form 
$myusername=$_POST['myusername']; 
$mypassword=$_POST['mypassword']; 
// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){
// Register $myusername, $mypassword and redirect to file "login_success.php"
$_SESSION['myusername'] = "$myusername";
$_SESSION['mypassword'] = "$mypassword";
print_r($_SESSION);
if ($_SESSION['myusername']) {
header("location:login_success.php");
}
}
else {
echo "Wrong Username or Password";
}
?>

login_success.php代码:

<?php
session_start();
include('connection.php');
if(!session_is_registered(myusername)){
header("location:main_login.php");
}
?>
<html>
<body>
Login Successful
</body>
</html>

我没有收到任何错误消息。它与数据库连接良好。我不确定问题出在哪里。我认为要么会话注册错误,要么与标头有关。

非常感谢您的帮助。

有几件事可能做错了。

首先,你有什么错误吗?您在php.ini文件中有显示错误吗?你知道如何从命令行查看日志文件吗?如果这不是一个选项的话?您可以查看apache日志来查找php会话错误,您应该在屏幕上看到一些内容。apache日志文件通常位于/var/log/https/access_logerror_log。如果查看您的VirtualHost,您将看到一个CustomLog,它指定日志文件所在的位置。

其次,不要使用session_register,这是旧的。如果您需要注册会话,请使用

$_SESSION['new_session'] = "value";

您可以使用$_SESSION['new_session']; 访问该会话

如果你需要检查是否有任何东西在会话中注册,请进行

print_r($_SESSION);

不要使用session_is_registered。如果您需要检查session_is_registered(myusername)是否已注册,请使用

if ($_SESSION['myusername']) {
}

代码中还有header("location,你必须确保在向网页输出之前使用该函数,它应该会抛出错误。请先尝试获取错误。