简体   繁体   中英

Login success when giving wrong username and password

Here is my code and it gives login success even after just clicking on submit button.

$username = isset($_POST['username']);
$password = isset($_POST['password']);
 //sql dtabase conn
    $conn = mysqli_connect("localhost","root","","login");
    //query the dtabase for user

   $result = mysqli_query($conn, "select * from users where username = 
    '$username' and password = '$password'")or die("failed to query database".mysqli_connect_error());

    $row = mysqli_fetch_array ($result);

    if($row['username'] == $username && $row['password'] == $password && ("" 
    !== $username || "" !== $password)){
        echo "Login success".$row['username'];
    }else{
        echo "Failed to login";
    }

I am a beginner at this. Please help me out

You're using isset to check the username / password post payload. This returns a true / false , not a value. So you'll never match a record in the DB and you'll never match the conditions of you credentials check (either a match or "" )

Try something like

$username = isset($_POST['username']) ? $_POST['username'] : false;

Which will set $username equal to the $_POST['username'] value OR to false if it's not set. Then you can test for it with something like:

if (($username && $password) and ($username == $row['username'] and $password == $row['password']))

Which should get you a lot closer than you are.

One other point-- you need to use some sort of hashing mechanism for the password. The way you've got it it looks like you're searching for a plaintext password value (unless you're hashing on the front end, I guess). Never store passwords in the DB as plaintext.

Your last condition in your IF statement || is true, the password is not empty because your isset() will always return a value and it will always be a success.

$username = $_POST['username'];
$password = $_POST['password'];

//sql dtabase conn
$conn = mysqli_connect("localhost","root","","login");
//query the dtabase for user

$result = mysqli_query($conn, "select * from users where username = 
'$username' and password = '$password'")or die("failed to query database".mysqli_connect_error());

$row = mysqli_fetch_array ($result);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM