登录脚本不起作用

时间:2014-04-21 22:30:51

标签: php mysql login

我的登录机制有点问题。在大多数情况下,它不会登录用户。如果用户是新注册的新用户,它可以正常工作,但所有其他用户名都没用。 Login.php页面如下:

<?php
//Disable error reporting 
error_reporting(0);
#Starting Session
session_start() ;
$_SESSION['username'] = 0 ;
$_SESSION['currentpage']="index.php" ;
$con=mysqli_connect('localhost','SouravBasuRoy','2525','MyteraArt');
$username = $_POST['username'];
$password = $_POST['password'] ;
$result = mysqli_query($con,'SELECT `username`, `password` FROM Customers');
while($row = mysqli_fetch_array($result))
{
if($row['username'] === $username && $row['password'] === $password)
{
$_SESSION['username']="$username";
setcookie('username' , $row['username']) ;
header("Location: http://localhost/loggedin.php") ;
}
else
{
header("Location: http://localhost/index.html") ;
}
}
?>

这是我用来检查用户是否登录的脚本。我复制粘贴在我的所有页面上。

<?php
$username = $_COOKIE['username'] ;
if ($username =="")
{
echo '<form name="login" action="login.php" method="post">
<label>Login</label>
<label for="Username">Username :<input type="text" name="username"></label>
<label for="Password">Password :<input type="password" name="password"></label>
<input type="submit">
</form>' ;
}
else
{
echo '<form action="logout.php">Logged in as : ' . $_COOKIE["username"] . ' ' . '<input type="submit" value="Logout"></form>' ;
}
?>

我遇到的问题是它无法正常使用

破坏脚本
echo $row['username];
echo $row['password'] ;

显示行的用户名和密码,但不会登录用户。

数据库结构是:

1 ID tinyint(4) 2命名tinytext 3发送电子邮件tinytext 4联系bigint(20) 5城市微文 6个用户名varchar(16) 7密码varchar(16) 8 isadmin tinyint(1)

1 个答案:

答案 0 :(得分:0)

你可能想要这样说

SELECT `username`, `password` FROM Customers

说这个

SELECT `username`, `password` FROM Customers WHERE username = ?

或者它会给你数据库中的所有用户...这就是你的表单给你带来问题的原因......因为它正在检查数据库中的第一个用户......


以下是我将如何更改您的代码...

更改此内容:

$result = mysqli_query($con,'SELECT `username`, `password` FROM Customers');
while($row = mysqli_fetch_array($result))
{
if($row['username'] === $username && $row['password'] === $password)
{
$_SESSION['username']="$username";
setcookie('username' , $row['username']) ;
header("Location: http://localhost/loggedin.php") ;
}
else
{
header("Location: http://localhost/index.html") ;
}

到此:

$query = 'SELECT `username`, `password` FROM Customers where username = ?';

if($stmt = $mysqli->prepare($query)){
    $stmt->bind_param('s',$username);
    $stmt->execute();
    $stmt->bind_result($get_username, $get_password);
    $stmt->fetch();
    $stmt->free_result();
    $stmt->close();
}

if($get_username === $username && $get_password === $password){
    $_SESSION['username']="$username";
    setcookie('username' , $row['username']) ;
    header("Location: http://localhost/loggedin.php");
    exit();
} else {
    header("Location: http://localhost/index.html");
    exit();
}

你在数据库中处理密码的方式有一个很大的缺陷......它们不应该是原始密码......请用盐,甚至胡椒来哈希。

相关问题