PHP密码验证正在被绕过

时间:2016-01-08 07:37:43

标签: php if-statement

我希望用户输入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 个答案:

答案 0 :(得分:4)

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重新加载网页..因此有必要重复比较。

另一种方法是这样做:

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

基本上它正在检查在第二个参数中传递的数组中是否定义了md5($userpassword)

有关in_array的更多信息:

  

in_array - 检查数组中是否存在值

     

用法 bool in_array(混合$ needle,数组$ haystack [,bool $ strict = FALSE])

     

链接 http://php.net/in_array