我在这里做了一个简单的登录脚本。有3个文件,1个是functions.php(包含登录功能),然后是userdashboard.php,其中包含一些用户功能,然后是另一个文件users.php,用于处理登录。
问题是,每当我登录时,登录成功但会引发错误:-未知变量用户名。
它应该显示登录人的用户名,我做错了什么?这是代码:-
函数.php
<?php
include 'dbconnector.php';
function checklogin($username,$password)
{
include 'dbconnector.php';
$userexists=false;
$username=mysql_real_escape_string($username);
$password=mysql_real_escape_string($password);
$password=md5($password);
$query="select * from f_users where username = '" . $username . "' and password = '" . $password . "'";
$result=mysql_query($query,$db) or die (mysql_error($db));
if(mysql_num_rows($result) > 0)
{
$userexists=true;
}
else
{
$userexists=false;
}
return $userexists;
}
用户仪表板.php
<?php
include('dbconnector.php');
session_start();
if(isset($_SESSION['logged']) && $_SESSION['logged']=1)
{
$_SESSION['username']=$username;
echo "Hello " . $username;
}
else
{
header('Location:login.php');
}
echo '<a href="logout.php">logout</a>';
?>
处理登录的文件。
include 'functions.php';
.
.
.
case 'login':
$username=$_POST['username'];
$password=$_POST['password'];
$username=mysql_real_escape_string($username);
$password=mysql_real_escape_string($password);
$password=md5($password);
if((!empty($username)) && (!empty($password)))
{
if(!checklogin($username,$password))
{
$_SESSION['logged']=1;
$_SESSION['username']=$username;
header('Location:userdashboard.php');
}
else
{
echo "Invalid combination of username and password";
echo "redirecting to the login page";
header('refresh:2;URL=login.php');
}
}
else
{
echo "username or password fields cannot be empty, redirecting";
header('refresh:2;URL=login.php');
}
break;
感谢您修复 Houssni。我这里有一个奇怪的错误。
即使我尝试了用户名和密码的有效组合,它总是会转到 else 部分并抛出错误。我在这里做错了什么?
$username=mysql_real_escape_string($username);
$password=mysql_real_escape_string($password);
$password=md5($password);
$query="select * from f_users where username = '" . $username . "' and password = '" . $password . "'";
$result=mysql_query($query,$db) or die (mysql_error($db));
if(mysql_num_rows($result) > 0)
{
session_start();
$_SESSION['logged']=1;
$_SESSION['username']=$username;
header('Location:userdashboard.php');
exit();
}
else
{
echo mysql_num_rows($result);
echo "Invalid combination of username and password";
echo "redirecting to the login page";
header('refresh:2;URL=login.php');
exit();
}