I use PHP code below for login without using database.
It redirects to home.php in two cases:
1. When I input correct username and password
2. When I input any character/s as username (except real username) and leave password textbox blank.
In other cases, except the second, code works properly.
How to make the code work properly in the second case?
<?php
session_start();
$userinfo = array(
'user1'=>'pass1',
);
if(isset($_GET['logout'])) {
$_SESSION['username'] = '';
header('Location: ' . $_SERVER['PHP_SELF']);
}
if(isset($_POST['username'])) {
if($userinfo[$_POST['username']] == $_POST['password']) {
$_SESSION['username'] = $_POST['username'];
header('Location: home.php');
}else {
header('Location: login.php');
}
}
?>
You could change
to
The reason it is failing is because if the username entered is not in your array, $userinfo[‘idontexist’] returns null, which evaluates to an empty string, so you are ultimately comparing
null == ''which is true.With the modified code, you are first checking to make sure the username entered actually exists in your array. If it does not, the password check is never run and they are redirected to the login page.
You could alternatively use === to compare the two, but a new vulnerability could be introduced where someone edits the form and removes the password field so that
$_POST['password']becomes null and then entering a non existent user would end up comparing null to null which would allow them to log in. Use the isset check to make sure the username exists in the array, then compare the password.Just for the sake of security, you may want to check to see if the password was empty and skip the password check and immediately return to the login page.
EDIT:
To allow the 2 cases you want, try:
if ((isset($userinfo[$_POST['username']]) && $userinfo[$_POST['username']] == $_POST['password']) || (!isset($userinfo[$_POST['username']]) && strlen($_POST['username']) > 0 && $_POST['password'] === '') {This checks if the username is in the array, if so make sure the password matches, OR check that the username is NOT in the array, and make sure the password is empty.