具有用户名和密码的关联数组数组、用户名、密码

2023-09-03 10:45:42 作者:『無可挑剔』

我将用户名和密码存储在关联数组中,我希望有一个登录系统,它可以检测错误的密码或用户名不存在。我有一个If Else代码,但是否有办法使代码更短?我在LoginValidator.php上有此代码

<?php
    $users = array(
        array("User" => "Test", "Password" => "123"),
        array("User" => "TestUser", "Password" => "x021"),
        array("User" => "Admin", "Password" => "admin"),
        array("User" => "user", "Password" => "user")
    );

    if ($_GET['username'] == $users[0]["User"] and $_GET['password'] == $users[0]["Password"]) {
        echo "Login Succesful";
    } else if ($_GET['username'] == $users[1]["User"] and $_GET['password'] == $users[1]["Password"]) {
        echo "Login Succesful";
    } else if ($_GET['username'] == $users[2]["User"] and $_GET['password'] == $users[2]["Password"]) {
        echo "Login Succesful";
    } else if ($_GET['username'] == $users[3]["User"] and $_GET['password'] == $users[3]["Password"]) {
        echo"Login Succesful";
    }
?>

这是login.html

<div class="login">
    <input type="text" placeholder="User Name" name="username"/>
    <input type="password" placeholder="Password" name="password"/>
    <input type="submit" value="Login"/>
</div>

推荐答案

Linux Shell编程及自动化运维实现之数组和函数

我会构建一个检查函数,这样您就可以更好地处理它。

<?php
    $users = array(
        array("User" => "Test", "Password" => "123"),
        array("User" => "TestUser", "Password" => "x021"),
        array("User" => "Admin", "Password" => "admin"),
        array("User" => "user", "Password" => "user")
    );

$_GET['username'] = 'Test';
$_GET['password'] = '123';


function check($user, $pw, $users) {
    $res = false;
    foreach($users as $row) {
        if ($row['User'] === $user && $row['Password'] === $pw) {
            $res = true;
        }
    }
    return $res;
}

echo check($_GET['username'], $_GET['password'], $users) ? 'Success' : 'Failed';

// output: Success