具有用户名和密码的关联数组 [英] Associative array with username and password

查看:0
本文介绍了具有用户名和密码的关联数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将用户名和密码存储在关联数组中,我希望有一个登录系统,它可以检测错误的密码或用户名不存在。我有一个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>

推荐答案

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

<?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

这篇关于具有用户名和密码的关联数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆