I want users to enter one of 4 passwords to get access to my site. The landing page is index.html and the redirect page should be home.html
I used the following code and I am using an if statement to hash the entered password and compare it with the 4 acceptable hases. If they match then I want the page to redirect. Otherwise I want to display a JS alert.
My issue is that even if the wrong password is entered, it still redirects with no alert.
//Take the values from the html form and assign them to variables
$ID = $_POST['name'];
$userpassword = $_POST['password'];
//Check to see if the password matches the hashes
if (md5($userpassword) === '5b5c45f1b9e444d9e441211cfb325270'
or '17434cf0d4ba816cd776ff8b0ec532f1'
or '7a94fda2a6e81a1693533e6dc8501b37'
or '2d8b2ba14eeb0ac1fe474d468b720771')
{
//Add the visitor name to our list
mysqli_query($connect, "INSERT INTO `visitor list` (`Visitor Name`) VALUES ('$ID')") or die("Error in INSERT: ".mysqli_error($connect));
echo "You have entered the correct password, congrats.";
// Redirect them to rest of site
header("Location: http://localhost:82/home.html");
die();
}
else {
echo "<script type='text/javascript'>alert('Wrong Password');</script>";
}
The code is only doing the comparison in for the first md5 hash but you have 4 conditions you want to satisfy so you would replace your if condition with this:
$hashedPassword = md5($userpassword);
if ( $hashedPassword == '5b5c45f1b9e444d9e441211cfb325270'
or $hashedPassword == '17434cf0d4ba816cd776ff8b0ec532f1'
or $hashedPassword == '7a94fda2a6e81a1693533e6dc8501b37'
or $hashedPassword == '2d8b2ba14eeb0ac1fe474d468b720771')
The reason why it wasn't working is because the way PHP interpreted code was like this:
if (false/true or true or true or true)
The md5 strings were seen as 'true' values. A string is only false if it is empty or it is equal "0" (but that's kind of a separate topic you can read about here .. so it is necessary to repeat the comparison.
An alternative way to do it would be to do this:
if (in_array(md5($userpassword), ['5b5c45f1b9e444d9e441211cfb325270', '17434cf0d4ba816cd776ff8b0ec532f1', '7a94fda2a6e81a1693533e6dc8501b37', '2d8b2ba14eeb0ac1fe474d468b720771'])
Basically it is checking if md5($userpassword)
is defined in the array that is passed in the second argument.
More info on in_array:
in_array — Checks if a value exists in an array
Usage bool in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] )