我希望用户输入 4 个密码之一才能访问我的网站。着陆页是index.html,重定向页应该是home.html
我使用了以下代码并使用 if 语句对输入的密码进行哈希处理并将其与 4 个可接受的 hase 进行比较。如果它们匹配,那么我希望页面重定向。否则我想显示一个 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>";
}
最佳答案
该代码仅对第一个 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”时才为假(但这是一个单独的主题,您可以阅读关于 here 的内容......因此有必要重复比较。
另一种方法是这样做:
if (in_array(md5($userpassword), ['5b5c45f1b9e444d9e441211cfb325270', '17434cf0d4ba816cd776ff8b0ec532f1', '7a94fda2a6e81a1693533e6dc8501b37', '2d8b2ba14eeb0ac1fe474d468b720771'])
基本上它是检查 md5($userpassword)
是否定义在传递给第二个参数的数组中。
关于 in_array 的更多信息:
in_array — Checks if a value exists in an array
Usage bool in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] )
关于PHP 密码验证被绕过,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34671754/