登录页面错误

时间:2017-05-16 03:15:35

标签: php html

这是我的登录页面。我可以在输入相关用户名和密码时登录,如果不匹配则无法登录。但事情是,当我没有输入任何用户名,密码并点击登录按钮时,我仍然有权登录。

这是索引页

<html>
<head>
<title>Login</title>
<link rel="stylesheet" type="text/css" href="login.css">
</head>

<body>
<div class="login-page">
    <form method="post" class="form" action="login.php"> 

      <input type="text" id="user" name="user" placeholder="username"/>
      <input type="password" id="pass" name="pass" placeholder="password"/>
      <button type="submit" name="submit" id="btn">login</button>

    </form>
</div>
</body>
</html>

这是login.php

<?php

    //get values passe from form in login.php file 
    $username = $_POST['user'];
    $password = $_POST['pass'];

    //to prevent sql injection
    $username = stripslashes($username);
    $password = stripslashes($password);
    $username = mysql_real_escape_string($username);
    $password = mysql_real_escape_string($password);

    //connect to the server and select database
    mysql_connect("localhost","root","");
    mysql_select_db('laboursalary');

    //query the database for user
    $result = mysql_query("SELECT * FROM login WHERE username= '$username' and password='$password'")
                or die("Failed to query database" .mysql_error());
    $row = mysql_fetch_array($result);
    if ($row['username']==$username && $row['password']==$password) {
        header("Location: ../projectdetails/index.php");

    } elseif ($row['username']=="" && $row['password']==""){
        echo "Failed to login";
    } else {
        echo "Failed to login";
    }


?>

2 个答案:

答案 0 :(得分:2)

这表示您的用户名和密码为空行。删除表中的那些行并更新下面的代码。

if ($username != "" && $password !=""){
//query the database for user
    $result = mysql_query("SELECT * FROM login WHERE username= '$username' and password='$password'")
                or die("Failed to query database" .mysql_error());
    $row = mysql_fetch_array($result);
    if ($row['username']==$username && $row['password']==$password) {
        header("Location: ../projectdetails/index.php");

    }  else {
        echo "Failed to login";
    }
}  else
        echo "Failed to login";
    }

注意:还要将mysql连接更改为mysqli或PDO。因为它在最新的PHP版本中已弃用。

答案 1 :(得分:2)

<?php
if(isset($_POST['submit']))
{
    //get values passe from form in login.php file 
    $username = mysql_real_escape_string($_POST['user']);
    $password = mysql_real_escape_string($_POST['pass']);


    //connect to the server and select database
    mysql_connect("localhost","root","");
    mysql_select_db('laboursalary');

    //query the database for user
    $result = mysql_query("SELECT * FROM login WHERE username= '$username' and password='$password'");
    $row = mysql_num_rows($result);         
   if($row == 1)
   {
        header("Location: ../projectdetails/index.php");

    } else {
        echo "Failed to login";
    }
}

?>