I have the usernames and password stored in an associative array, I want to have a login system where it detects wrong password or the username does not exist. I have an if else code but is there anyway to make the code more shorter? I have this code on 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";
}
?>
This is the login.html
<div >
<input type="text" placeholder="User Name" name="username"/>
<input type="password" placeholder="Password" name="password"/>
<input type="submit" value="Login"/>
CodePudding user response:
One of many options, you can do this using the array_column
and in_array
functions
if (in_array($_GET['username'], array_column($users, 'User')) and in_array($_GET['password'], array_column($users, 'Password'))) {
echo 'Login Succesful';
}
CodePudding user response:
I present the solution below. This solution allows you to manage the request code.
<?php
$users = [["User" => "Test", "Password" => "123"],
["User" => "TestUser", "Password" => "x021"],
["User" => "Admin", "Password" => "admin"],
["User" => "user", "Password" => "user"]
];
$get_user = 'TestUser';
$get_password = 'x021';
foreach($users as $key => $value) {
//if ($_GET['username'] == $value["User"] and $_GET['password'] == $value["Password"]) {
//echo "Login Succesful"; // for you
//}
if ($get_user == $value["User"] and $get_password == $value["Password"]) {
echo "Login Succesful"; // for test
}
}
https://wtools.io/php-sandbox/bAdy
CodePudding user response:
Use foreach
for $users
array
foreach($users as $uu){
if($uu['User'] == $_GET['username'] && $uu['Password'] == $_GET['password']){
echo "Login Succesful";
}
}
CodePudding user response:
I suggest you a combination of current
and array_filter
such as what follows:
$username = $_GET["username"];
$password = $_GET["password"];
$check = current(array_filter($users, function($element) use ($username, $password){
return ($element["User"] == $username and $element["Password"] == $password);
}));
if(count($check) == 1){
echo("Login Successful");
}else{
echo("Oopsy doopsy");
}