简体   繁体   中英

My PHP login system still Logging in even if the password or username is incorrect

Still loggin in even if the username and password is incorrect and also logins even if the value is null

<?php 

    $hostname = "localhost";
    $username = "root";
    $password = "";
    $dbname = "login";
    $conn = mysqli_connect($hostname, $username, $password, $dbname);
    if (!$conn) {
        die ("unable to connect");
    }

    if ($_POST) {
        $uname = $_POST ["username"];
        $pass = $_POST ["password"];

        $sql = "SELECT * FROM users WHERE username = '$uname' AND password = '$pass' LIMIT 1 ";
        $result = mysqli_query($conn, $sql);
        if (mysqli_num_rows($result) == 1){
            include("graph.php");
        } else {
            echo "Incorrect"; 
        }
    }
 ?>

First of all and very important it that you are open to SQL Injection attack , so you should use prepared statements, here is how should use your code, but instead of echo "Incorrect"; you should render different answer for each case:

<?php

    $hostname = "localhost";
    $username = "root";
    $password = "";
    $dbname = "login";
    $conn = mysqli_connect($hostname, $username, $password, $dbname);
    if (!$conn) {
        die ("unable to connect");
    }

    if (isset($_POST["username"]) && isset($_POST["password"])) { // Check if you have posted data via POST
        $uname = $_POST["username"];
        $pass = $_POST["password"];

        $sql = "SELECT * FROM users WHERE username = ? AND password = ? LIMIT 1 ";

        if($stmt = $conn->prepare($sql)) { // Check for MySQL errors
            $stmt->bind_param('ss', $uname, $pass);
            if ($stmt->execute()) {
                $stmt->close();
                include("graph.php");
            } else { // There is a problem with your SELECT // bind params
                echo "Incorrect";
            }
        } else { // You should handle mysql errors here
            echo "Incorrect";
        }
    } else { // You don't have POST data
        echo "Incorrect";
    }
 ?>

Prepared statements

Like @Kuya notice you have and many other problems, there is a lot of tutorials in Google about implementation of login system.

You must check the post request with isset() in php like this :

<?php 
if (isset($_POST["username"] && isset($_POST["password"]))) {
     //..... Your code here
}else {
    echo "Incorrect password or username";
}
?>

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