PHP密码验证正在被绕过

3
我希望用户输入4个密码之一以访问我的网站。登陆页面是index.html,重定向页面应该是home.html。
我使用了以下代码,使用if语句对输入的密码进行哈希,并将其与4个可接受的哈希进行比较。如果匹配,则希望页面重定向。否则,我希望显示JS警报。
我的问题是,即使输入错误的密码,它仍然会重定向而没有警报。
//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>";
}
1个回答

4

这段代码只对第一个MD5哈希进行比较,但是你有4个条件需要满足,因此你需要将if条件替换为以下内容:

$hashedPassword = md5($userpassword);
if (   $hashedPassword == '5b5c45f1b9e444d9e441211cfb325270' 
    or $hashedPassword == '17434cf0d4ba816cd776ff8b0ec532f1' 
    or $hashedPassword == '7a94fda2a6e81a1693533e6dc8501b37' 
    or $hashedPassword == '2d8b2ba14eeb0ac1fe474d468b720771') 

原因是PHP解释代码的方式是这样的:
if (false/true or true or true or true) 

md5字符串被视为“真”值。如果字符串为空或等于“0”,则字符串才为false(但这是一个单独的话题,你可以在此处阅读有关该主题的更多信息)...因此需要重复比较。

另一种方法是这样做:

if (in_array(md5($userpassword), ['5b5c45f1b9e444d9e441211cfb325270', '17434cf0d4ba816cd776ff8b0ec532f1', '7a94fda2a6e81a1693533e6dc8501b37', '2d8b2ba14eeb0ac1fe474d468b720771'])

基本上,它是检查在第二个参数中传递的数组中是否定义了md5($userpassword)
关于in_array的更多信息:
in_array-检查数组中是否存在某个值
用法:bool in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] )
链接:http://php.net/in_array

太棒了,它能正常工作!我会尽快将其标记为答案。顺便问一下,你知道如何防止未输入正确密码就访问重定向页面吗? - Badrush
1
使用PHP会话。这个主题太深入了,无法在这个问题中涵盖,但是在Google上搜索一下,你会找到一些好的教程/解决方案,如果遇到困难,请回来在StackOverflow上提一个新问题。 - Clay

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接