使用多个密码进行简单的受密码保护的页面

时间:2015-12-03 19:40:55

标签: php html forms passwords password-protection

我正在尝试使用PHP保护我网站中的某些页面,但不创建数据库或用户名。

我按照对此帖发表评论的说明:What is the best way to password protect folder/page using php without a db or username 哪个效果很好!但我想更进一步,更改代码,以便在同一页面上接受多个密码。这可能吗?

我想它会是这样的:检查$ password数组中是否存在检索到的值

//access.php

<?php
//put sha1() encrypted password here - example is 'hello'
$password = 'aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d';

session_start();
if (!isset($_SESSION['loggedIn'])) {
   $_SESSION['loggedIn'] = false;
}

if (isset($_POST['password'])) {
  if (sha1($_POST['password']) == $password) {
    $_SESSION['loggedIn'] = true;
  } else {
     die ('Incorrect password');
  }
} 

if (!$_SESSION['loggedIn']): ?>

<html><head><title>Login</title></head>
<body>
 <p>You need to login</p>
 <form method="post">
  Password: <input type="password" name="password"> <br />
  <input type="submit" name="submit" value="Login">
</form>
</body>

<?php
exit();
endif;
?> 

2 个答案:

答案 0 :(得分:1)

创建一组密码,然后使用in_array函数检查用户密码是否在那里。

要改变的路线是:

$passwords = array("aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d", "aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d", "etc..");

if (in_array(sha1($_POST['password']), $passwords)) {

答案 1 :(得分:0)

您可以将密码设置为数组并循环播放以检查它们

$passwords = [
    'aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d',
    'aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d',
    'aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d',
];


if (isset($_POST['password'])) {

  $result = false;

  foreach($passwords as $password){
      if (sha1($_POST['password']) == $password) {
        $result = true;
     }
  }

  if($result) {
     $_SESSION['loggedIn'] = true;
  } else {
     die ('Incorrect password');
  }

}