How would I add a second user to login on this php file?

Viewed 27

I am trying to add a second login to this PHP program with the username being "user". The primary login with the username "admin" works and logs in just fine, however whenever I try to login with the user login, I get an error saying the username or password was incorrect. How would I make it so that I can login with both the "user" and "admin" account? This all needs to be done with an array written in the main code.

<?php
    
    $errors = array();
    $isLoggedIn = false;
    
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $users = array("user" => '$2y$10$yHL4GKr4pKxnBJ1L2xlqYuI/k0kviae2NbIQNJLFeXgVclT2hZeDi');
        $users = array("admin" => '$2y$10$yHL4GKr4pKxnBJ1L2xlqYuI/k0kviae2NbIQNJLFeXgVclT2hZeDi');
        $required = array("username", "pass");
    
        foreach ($required as $key => $value) {
            if (!isset($_POST[$value]) || empty($_POST[$value])) {
                $errors[] = "please fill out the form";
            }
        }
    
        if (array_key_exists($_POST['username'], $users)) {
            $userPassword = $_POST['pass'];
            $dbPass = $users[$_POST['username']];
    
            if (password_verify($userPassword, $dbPass)) {
                $isLoggedIn = true;
            } else {
                $isLoggedIn = false;
                $errors[] = "Username not found or password incorrect";
            }
        } else {
            $errors[] = "Username not found or password incorrect";
        }
    }
    
    require_once("Template.php");
    
    $page = new Template("My Login");
    $page->addHeadElement("<link rel=\"stylesheet\" href=\"styles.css\">");
    $page->addHeadElement("<script src='hello.js'></script>");
    $page->finalizeTopSection();
    $page->finalizeBottomSection();
    
    print $page->getTopSection();
    
    if (count($errors) > 0) {
        foreach ($errors as $error) {
            print "$error<br/>" . PHP_EOL;
        }
    } else if ($isLoggedIn === true) {
        print "Hello, you are logged in";
    }
    
    ?>
    
    <form action="login_action.php" method="POST" class="form-signin">
        <h1>Please sign in</h1>
        <label for="inputUser">Username</label>
        <input type="text" name="username" id="inputUser">
        <label for="inputPassword">Password</label>
        <input type="password" name="pass" id="inputPassword">
        <button type="submit">Sign In</button>
    </form>
    
    <?php print $page->getBottomSection(); ?>
1 Answers

You're overwriting the $users array instead of adding more values, I recommend reading the documentation and learning how PHP handles arrays and the array function.

$users = array(
    "user"  => '$2y$10$yHL4GKr4pKxnBJ1L2xlqYuI/k0kviae2NbIQNJLFeXgVclT2hZeDi',
    "admin" => '$2y$10$yHL4GKr4pKxnBJ1L2xlqYuI/k0kviae2NbIQNJLFeXgVclT2hZeDi'
);
Related