ncirl.eva ncirl.eva - 1 year ago 112
PHP Question

Any unregistered user can login (PHP)

I'm working on a login for my website, when I login it doesn't check to see if the user already exists in the database. It allows anyone to sign in even if you haven't registered.

This is the code for the login.

<?php


//database details
$servername = "localhost";
$username = "myname";
$password = "******";
$dbname = "mydb";


// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
session_start();

if(isset($_POST['email']))

{
$email = $_POST ['email'];
$password =$_POST ['password'];


$query = "SELECT * FROM Users WHERE Email='$email' AND Password='$password'";


$result = mysqli_query($conn, $query);





if($result==1)
{

header('Location: profile.php');
exit();
}

else
{

header('Location: failedlogin.html');
exit();
}


}


?>

Answer Source

Your code never checks if the user account exists in the database. It only checks if the query was executed without error. This should work(untested):

$query = "SELECT * FROM Users WHERE Email='$email' AND Password='$password' LIMIT 1";
if($result = mysqli_query($conn, $query)){

    if(mysqli_num_rows($result) > 0){

        //user account exists
        $member = mysqli_fetch_array($result, MYSQLI_ASSOC);
        $email = $member["Email"];

    } else {

        //user account does not exist

    }

} else {

    echo "Error executing database query.";

}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download