Search code examples
phpauthenticationmultiple-users

PHP Login system with multiple accounts


I want to make a basic PHP Login system with multiple accounts. My problem is when you try to login as user1 with the user2's password, the code somewhy lets you. But I don't want to allow you to login with another password. Any idea how to make it?

Code:

<?PHP
$local_user1 = "user1"; 
$local_password1 = "123"; 
$local_user2 = "user2"; 
$local_password2 = "456"; 
$local_user3 = "user3"; 
$local_password3 = "789"; 
if (isset($_POST['login']))
{
    $u_post = $_POST['username'];
    $p_post = $_POST['password'];

    if ($local_user1 == $u_post || $local_user2 == $u_post || $local_user3 == $u_post) 
    {
        if ($local_password1 == $p_post || $local_password2 == $p_post || $local_password3 == $p_post) 
        {
            echo "hello, ".$local_user."!";   
            die();
        }
        echo "Te username or password are not correct !";
        die(); 
    }
    else 
    {
        echo "Te username or password are not correct !";
        die(); 
    }
}
?>
<html> 
<body> 
    <form action="" method="POST" >
        <input type="text"  name="username" placeholder="Enter username" /> 
        </br> 
        <input type="password" name="password" placeholder="Enter password" />
        </br> 
        <input type="submit" name="login" /> 
    </form>
</body>

Solution

  • For simple purposes, you need to rearrange your if statements

    if (($user == "user1" && $pass == "pass1") || ($user == "user2" && $pass == "pass2") || ($user == "user3" && $pass == "pass3")) {
        //Login successful
    }
    

    That way it checks to see if it matches the username and password based on a set of username and passwords and not just checks to see whether A username is correct and A password is correct, however you should redesign your system to use a database because if you are to have multiple users, you cannot simply add one of those if conditions for every user