用密码保护 PHP 页面的简单方法?

发布于 2024-10-01 16:08:01 字数 1705 浏览 3 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

毁虫ゝ 2024-10-08 16:08:02

这有点晚了,但我想回复以防其他人访问此页面并发现最高回复有点偏离。我对系统做了一点改进。请注意,它仍然不是非常安全,但它是一个改进。

首先准备您的密码盐文件:

hash_generate.php:

 <?php

 $user = "Username"; // please replace with your user
 $pass = "Password"; // please replace with your passwd
 // two ; was missing

 $useroptions = ['cost' => 8,];
 $userhash    = password_hash($user, PASSWORD_BCRYPT, $useroptions);
 $pwoptions   = ['cost' => 8,];
 $passhash    = password_hash($pass, PASSWORD_BCRYPT, $pwoptions);

 echo $userhash;
 echo "<br />";
 echo $passhash;

 ?>

获取输出$userhash$passhash并将它们放入两个文本文件中:user.php。分别为 txt 和 pass.txt。其他人建议将这些文本文件放在 public_html 之上,这是一个好主意,但我只是使用 .htaccess 并将它们存储在名为“stuff”的文件夹中

.htaccess

 deny from all

现在没有人可以查看哈希值。接下来是你的index.php:

index.php:

<?php
$user = ""; //prevent the "no index" error from $_POST
$pass = "";
if (isset($_POST['user'])) { // check for them and set them so
    $user = $_POST['user'];
}
if (isset($_POST['pass'])) { // so that they don't return errors
    $pass = $_POST['pass'];
}    

$useroptions = ['cost' => 8,]; // all up to you
$pwoptions   = ['cost' => 8,]; // all up to you
$userhash    = password_hash($user, PASSWORD_BCRYPT, $useroptions); // hash entered user
$passhash    = password_hash($pass, PASSWORD_BCRYPT, $pwoptions);  // hash entered pw
$hasheduser  = file_get_contents("stuff/user.txt"); // this is our stored user
$hashedpass  = file_get_contents("stuff/pass.txt"); // and our stored password


if ((password_verify($user, $hasheduser)) && (password_verify($pass,$hashedpass))) {

    // the password verify is how we actually login here
    // the $userhash and $passhash are the hashed user-entered credentials
    // password verify now compares our stored user and pw with entered user and pw

    include "pass-protected.php";

} else { 
    // if it was invalid it'll just display the form, if there was never a $_POST
    // then it'll also display the form. that's why I set $user to "" instead of a $_POST
    // this is the right place for comments, not inside html
    ?>  
    <form method="POST" action="index.php">
    User <input type="text" name="user"></input><br/>
    Pass <input type="password" name="pass"></input><br/>
    <input type="submit" name="submit" value="Go"></input>
    </form>
    <?php 
} 

This is a bit late but I wanted to reply in case anyone else came upon this page and found that the highest reply was a bit off. I have improved upon the system just a tad bit. Note, it is still not amazingly secure but it is an improvement.

First prepare your password salts file:

hash_generate.php:

 <?php

 $user = "Username"; // please replace with your user
 $pass = "Password"; // please replace with your passwd
 // two ; was missing

 $useroptions = ['cost' => 8,];
 $userhash    = password_hash($user, PASSWORD_BCRYPT, $useroptions);
 $pwoptions   = ['cost' => 8,];
 $passhash    = password_hash($pass, PASSWORD_BCRYPT, $pwoptions);

 echo $userhash;
 echo "<br />";
 echo $passhash;

 ?>

Take your output $userhash and $passhash and put them in two text files: user.txt and pass.txt, respectively. Others have suggested putting these text files away above public_html, this is a good idea but I just used .htaccess and stored them in a folder called "stuff"

.htaccess

 deny from all

Now no one can peek into the hash. Next up is your index.php:

index.php:

<?php
$user = ""; //prevent the "no index" error from $_POST
$pass = "";
if (isset($_POST['user'])) { // check for them and set them so
    $user = $_POST['user'];
}
if (isset($_POST['pass'])) { // so that they don't return errors
    $pass = $_POST['pass'];
}    

$useroptions = ['cost' => 8,]; // all up to you
$pwoptions   = ['cost' => 8,]; // all up to you
$userhash    = password_hash($user, PASSWORD_BCRYPT, $useroptions); // hash entered user
$passhash    = password_hash($pass, PASSWORD_BCRYPT, $pwoptions);  // hash entered pw
$hasheduser  = file_get_contents("stuff/user.txt"); // this is our stored user
$hashedpass  = file_get_contents("stuff/pass.txt"); // and our stored password


if ((password_verify($user, $hasheduser)) && (password_verify($pass,$hashedpass))) {

    // the password verify is how we actually login here
    // the $userhash and $passhash are the hashed user-entered credentials
    // password verify now compares our stored user and pw with entered user and pw

    include "pass-protected.php";

} else { 
    // if it was invalid it'll just display the form, if there was never a $_POST
    // then it'll also display the form. that's why I set $user to "" instead of a $_POST
    // this is the right place for comments, not inside html
    ?>  
    <form method="POST" action="index.php">
    User <input type="text" name="user"></input><br/>
    Pass <input type="password" name="pass"></input><br/>
    <input type="submit" name="submit" value="Go"></input>
    </form>
    <?php 
} 
人生百味 2024-10-08 16:08:02

这是一个非常简单的方法。创建两个文件:

protect-this.php

<?php
    /* Your password */
    $password = 'MYPASS';

    if (empty($_COOKIE['password']) || $_COOKIE['password'] !== $password) {
        // Password not set or incorrect. Send to login.php.
        header('Location: login.php');
        exit;
    }
?>

login.php:

<?php
    /* Your password */
    $password = 'MYPASS';

    /* Redirects here after login */
    $redirect_after_login = 'index.php';

    /* Will not ask password again for */
    $remember_password = strtotime('+30 days'); // 30 days

    if (isset($_POST['password']) && $_POST['password'] == $password) {
        setcookie("password", $password, $remember_password);
        header('Location: ' . $redirect_after_login);
        exit;
    }
?>
<!DOCTYPE html>
<html>
<head>
    <title>Password protected</title>
</head>
<body>
    <div style="text-align:center;margin-top:50px;">
        You must enter the password to view this content.
        <form method="POST">
            <input type="text" name="password">
        </form>
    </div>
</body>
</html>

然后在您想要的文件顶部添加 protect-this.php保护:

// Password protect this content
require_once('protect-this.php');

结果示例:

password protected php

填写正确的密码后,用户将被带到index.php。密码保存 30 天。

PS:重点不在于安全,而在于实用。黑客可以暴力破解这一点。用它来阻止普通用户。不要用它来保护敏感信息。

Here's a very simple way. Create two files:

protect-this.php

<?php
    /* Your password */
    $password = 'MYPASS';

    if (empty($_COOKIE['password']) || $_COOKIE['password'] !== $password) {
        // Password not set or incorrect. Send to login.php.
        header('Location: login.php');
        exit;
    }
?>

login.php:

<?php
    /* Your password */
    $password = 'MYPASS';

    /* Redirects here after login */
    $redirect_after_login = 'index.php';

    /* Will not ask password again for */
    $remember_password = strtotime('+30 days'); // 30 days

    if (isset($_POST['password']) && $_POST['password'] == $password) {
        setcookie("password", $password, $remember_password);
        header('Location: ' . $redirect_after_login);
        exit;
    }
?>
<!DOCTYPE html>
<html>
<head>
    <title>Password protected</title>
</head>
<body>
    <div style="text-align:center;margin-top:50px;">
        You must enter the password to view this content.
        <form method="POST">
            <input type="text" name="password">
        </form>
    </div>
</body>
</html>

Then require protect-this.php on the TOP of the files you want to protect:

// Password protect this content
require_once('protect-this.php');

Example result:

password protect php

After filling the correct password, user is taken to index.php. The password is stored for 30 days.

PS: It's not focused to be secure, but to be pratical. A hacker can brute-force this. Use it to keep normal users away. Don't use it to protect sensitive information.

清音悠歌 2024-10-08 16:08:02
<?php
$username = "the_username_here";
$password = "the_password_here";
$nonsense = "supercalifragilisticexpialidocious";

if (isset($_COOKIE['PrivatePageLogin'])) {
   if ($_COOKIE['PrivatePageLogin'] == md5($password.$nonsense)) {
?>

    <!-- LOGGED IN CONTENT HERE -->

<?php
      exit;
   } else {
      echo "Bad Cookie.";
      exit;
   }
}

if (isset($_GET['p']) && $_GET['p'] == "login") {
   if ($_POST['user'] != $username) {
      echo "Sorry, that username does not match.";
      exit;
   } else if ($_POST['keypass'] != $password) {
      echo "Sorry, that password does not match.";
      exit;
   } else if ($_POST['user'] == $username && $_POST['keypass'] == $password) {
      setcookie('PrivatePageLogin', md5($_POST['keypass'].$nonsense));
      header("Location: $_SERVER[PHP_SELF]");
   } else {
      echo "Sorry, you could not be logged in at this time.";
   }
}
?>

以及页面上的登录表单...
(在同一页面上,上面^发布的代码的正下方)

<form action="<?php echo $_SERVER['PHP_SELF']; ?>?p=login" method="post">
<label><input type="text" name="user" id="user" /> Name</label><br />
<label><input type="password" name="keypass" id="keypass" /> Password</label><br />
<input type="submit" id="submit" value="Login" />
</form>
<?php
$username = "the_username_here";
$password = "the_password_here";
$nonsense = "supercalifragilisticexpialidocious";

if (isset($_COOKIE['PrivatePageLogin'])) {
   if ($_COOKIE['PrivatePageLogin'] == md5($password.$nonsense)) {
?>

    <!-- LOGGED IN CONTENT HERE -->

<?php
      exit;
   } else {
      echo "Bad Cookie.";
      exit;
   }
}

if (isset($_GET['p']) && $_GET['p'] == "login") {
   if ($_POST['user'] != $username) {
      echo "Sorry, that username does not match.";
      exit;
   } else if ($_POST['keypass'] != $password) {
      echo "Sorry, that password does not match.";
      exit;
   } else if ($_POST['user'] == $username && $_POST['keypass'] == $password) {
      setcookie('PrivatePageLogin', md5($_POST['keypass'].$nonsense));
      header("Location: $_SERVER[PHP_SELF]");
   } else {
      echo "Sorry, you could not be logged in at this time.";
   }
}
?>

And the login form on the page...
(On the same page, right below the above^ posted code)

<form action="<?php echo $_SERVER['PHP_SELF']; ?>?p=login" method="post">
<label><input type="text" name="user" id="user" /> Name</label><br />
<label><input type="password" name="keypass" id="keypass" /> Password</label><br />
<input type="submit" id="submit" value="Login" />
</form>
可爱暴击 2024-10-08 16:08:02

我会简单地查找 $_GET 变量,如果不正确则重定向用户。

<?php
$pass = $_GET['pass'];
if($pass != 'my-secret-password') {
  header('Location: http://www.staggeringbeauty.com/');
}
?>

现在,如果此页面位于:http://example.com/secrets/files.php

您现在可以通过以下方式访问它:http://example.com/secrets/ files.php?pass=my-secret-password 请记住,这不是最有效或最安全的方法,但它仍然是一种简单快捷的方法。 (另外,我知道我的答案已经过时,但其他人看到这个问题可能会发现它很有价值)

I would simply look for a $_GET variable and redirect the user if it's not correct.

<?php
$pass = $_GET['pass'];
if($pass != 'my-secret-password') {
  header('Location: http://www.staggeringbeauty.com/');
}
?>

Now, if this page is located at say: http://example.com/secrets/files.php

You can now access it with: http://example.com/secrets/files.php?pass=my-secret-password Keep in mind that this isn't the most efficient or secure way, but nonetheless it is a easy and fast way. (Also, I know my answer is outdated but someone else looking at this question may find it valuable)

海螺姑娘 2024-10-08 16:08:02
Some easy ways:
Use Apache's digest authorization.
Use lighttpd's digest authorization.
Use php's header digest authorization.

如果你愿意,你也可以做到只有某些 ip 地址可以登录..:) 使用 lighttpd 真的很容易

更新:我很快就会发布一些示例,所以不要因为没有示例而投票否决,我只需要获取一些示例这个答案。

如果您想使用会话,以下是最好的方法:

# admin.php
session_start();
if(!$_SESSION["AUTH"])
    require_once "login.php";
# Do stuff, we are logged in..

# login.php
session_start();
if($_REQUEST["username"] == "user" && $_REQUEST["password"] == "pass")
    $_SESSION["AUTH"] = true;
else $_SESSION["AUTH"] = false; # This logs you out if you visit this login script page without login details.

if($_SESSION["AUTH"])
    require_once "admin.php";

此方法不包含上面的示例,但您对此方法感兴趣。其他方法示例仍然存在,我没有足够的时间来获取 apache 或 lighttpd 设置以及 php 标头身份验证: http://php.net/manual/en/features.http-auth.php 就可以了。

Some easy ways:
Use Apache's digest authorization.
Use lighttpd's digest authorization.
Use php's header digest authorization.

If you want you can also make it so only certain ip addresses can login.. :) really easy with lighttpd

Update: I will post some examples soon, so don't vote down for no examples, i just need to get some down for this answer.

If you want to use sessions the following is the best way to go:

# admin.php
session_start();
if(!$_SESSION["AUTH"])
    require_once "login.php";
# Do stuff, we are logged in..

# login.php
session_start();
if($_REQUEST["username"] == "user" && $_REQUEST["password"] == "pass")
    $_SESSION["AUTH"] = true;
else $_SESSION["AUTH"] = false; # This logs you out if you visit this login script page without login details.

if($_SESSION["AUTH"])
    require_once "admin.php";

This method does not contain the examples for above but you seamed interested in this method. The other method examples are still to come, I have not got enough time to get it for apache or lighttpd settings and the php header auth: http://php.net/manual/en/features.http-auth.php Will do.

静谧 2024-10-08 16:08:02

保护文件的简单方法不需要单独的登录页面 - 只需将其添加到页面顶部:

将 Secretuser 和 Secretpassword 更改为您的用户/密码。

$user = $_POST['user'];
$pass = $_POST['pass'];

if(!($user == "secretuser" && $pass == "secretpassword"))
{
    echo '<html><body><form method="POST" action="'.$_SERVER['REQUEST_URI'].'">
            Username: <input type="text" name="user"></input><br/>
            Password: <input type="password" name="pass"></input><br/>
            <input type="submit" name="submit" value="Login"></input>
            </form></body></html>';
    exit();
}

A simple way to protect a file with no requirement for a separate login page - just add this to the top of the page:

Change secretuser and secretpassword to your user/password.

$user = $_POST['user'];
$pass = $_POST['pass'];

if(!($user == "secretuser" && $pass == "secretpassword"))
{
    echo '<html><body><form method="POST" action="'.$_SERVER['REQUEST_URI'].'">
            Username: <input type="text" name="user"></input><br/>
            Password: <input type="password" name="pass"></input><br/>
            <input type="submit" name="submit" value="Login"></input>
            </form></body></html>';
    exit();
}
花伊自在美 2024-10-08 16:08:02
</html>
<head>
  <title>Nick Benvenuti</title>
  <link rel="icon" href="img/xicon.jpg" type="image/x-icon/">
  <link rel="stylesheet" href="CSS/main.css">
  <link rel="stylesheet" href="CSS/normalize.css">
  <script src="JS/jquery-1.12.0.min.js" type="text/javascript"></script>
</head>
<body>
<div id="phplogger">
  <script type="text/javascript">
  function tester() {
  window.location.href="admin.php";
  }
  function phpshower() {
  document.getElementById("phplogger").classList.toggle('shower');
  document.getElementById("phplogger").classList.remove('hider');
  }
  function phphider() {
  document.getElementById("phplogger").classList.toggle('hider');
  document.getElementById("phplogger").classList.remove('shower');
  }
</script>
<?php 
//if "login" variable is filled out, send email
  if (isset($_REQUEST['login']))  {

  //Login info
  $passbox = $_REQUEST['login'];
  $password = 'blahblahyoudontneedtoknowmypassword';

  //Login
  if($passbox == $password) {

  //Login response
  echo "<script text/javascript> phphider(); </script>";
  }
 }
?>
<div align="center" margin-top="50px">
<h1>Administrative Access Only</h1>
<h2>Log In:</h2>
 <form method="post">
  Password: <input name="login" type="text" /><br />
  <input type="submit" value="Login" id="submit-button" />
  </form>
</div>
</div>
<div align="center">
<p>Welcome to the developers and admins page!</p>
</div>
</body>
</html>

基本上,我在这里所做的就是在一个 php 文件中创建一个页面,当您输入密码(如果正确)时,它将隐藏密码屏幕并向前显示受保护的内容。然后是 css,这是一个至关重要的部分,因为它创建了隐藏和显示页面不同部分的类。

  /*PHP CONTENT STARTS HERE*/
  .hider {
  visibility:hidden;
  display:none;
  }

  .shower {
  visibility:visible;
  }

  #phplogger {
  background-color:#333;
  color:blue;
  position:absolute;
  height:100%;
  width:100%;
  margin:0;
  top:0;
  bottom:0;
  }
  /*PHP CONTENT ENDS HERE*/
</html>
<head>
  <title>Nick Benvenuti</title>
  <link rel="icon" href="img/xicon.jpg" type="image/x-icon/">
  <link rel="stylesheet" href="CSS/main.css">
  <link rel="stylesheet" href="CSS/normalize.css">
  <script src="JS/jquery-1.12.0.min.js" type="text/javascript"></script>
</head>
<body>
<div id="phplogger">
  <script type="text/javascript">
  function tester() {
  window.location.href="admin.php";
  }
  function phpshower() {
  document.getElementById("phplogger").classList.toggle('shower');
  document.getElementById("phplogger").classList.remove('hider');
  }
  function phphider() {
  document.getElementById("phplogger").classList.toggle('hider');
  document.getElementById("phplogger").classList.remove('shower');
  }
</script>
<?php 
//if "login" variable is filled out, send email
  if (isset($_REQUEST['login']))  {

  //Login info
  $passbox = $_REQUEST['login'];
  $password = 'blahblahyoudontneedtoknowmypassword';

  //Login
  if($passbox == $password) {

  //Login response
  echo "<script text/javascript> phphider(); </script>";
  }
 }
?>
<div align="center" margin-top="50px">
<h1>Administrative Access Only</h1>
<h2>Log In:</h2>
 <form method="post">
  Password: <input name="login" type="text" /><br />
  <input type="submit" value="Login" id="submit-button" />
  </form>
</div>
</div>
<div align="center">
<p>Welcome to the developers and admins page!</p>
</div>
</body>
</html>

Basically what I did here is make a page all in one php file where when you enter the password if its right it will hide the password screen and bring the stuff that protected forward. and then heres the css which is a crucial part because it makes the classes that hide and show the different parts of the page.

  /*PHP CONTENT STARTS HERE*/
  .hider {
  visibility:hidden;
  display:none;
  }

  .shower {
  visibility:visible;
  }

  #phplogger {
  background-color:#333;
  color:blue;
  position:absolute;
  height:100%;
  width:100%;
  margin:0;
  top:0;
  bottom:0;
  }
  /*PHP CONTENT ENDS HERE*/
夏有森光若流苏 2024-10-08 16:08:02

这会在登录后将密码存储在历史记录中!

您可以在 php 代码中指定密码,以便只有拥有秘密 URL 的用户才能访问:

mywebsite.com/private.php?pass=secret

在您的登录保护文件中:

<?php
     if(isset($_GET["pass"]) && $_GET["pass"]=="secret"){
           //put your code here
     }
     else{
           echo "you're not allowed to access this page";
     }
?>

This stores the password in history after login!

You can specify a password in your php code so only users that have the secret url can access:

mywebsite.com/private.php?pass=secret

in your login-protected file:

<?php
     if(isset($_GET["pass"]) && $_GET["pass"]=="secret"){
           //put your code here
     }
     else{
           echo "you're not allowed to access this page";
     }
?>
醉态萌生 2024-10-08 16:08:02

即使在 2023 年,我发现自己也在编写用于调试日志记录和其他测试任务的小型 PHP 脚本,我宁愿保留某种保护,所以这里有一个登录脚本,可以让您完成所有这些工作。它位于 GitHub 上 https://github.com/Mugane/simple-php-auth

<?php
    /* 
       Login system in a single php file.
       Tabs, obviously; Configurable editors exist for those with spacing hangups.
       © 2023 Peter Kionga-Kamau. MIT License with this comment block left intact.
       https://github.com/Mugane/simple-php-auth
    */
    // ----------------- Begin Login Section (add protected content after this section) -----------------
    @session_start();
        // --- start modifiable variables: ---
        // $credentials contains unsalted hash for the login "admin" and "password" (replace with your hashed credentials):
        // Generate a hash in bash: echo $(echo -n "texttohash" | sha256sum | cut -d " " -f1)
    $credentials = array('8c6976e5b5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918' => '5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8');
    $salt        = '';    // add random string here to salt your password hashes (vaguely more secure)
    $max_logins  = 5;     // maximum number of failed login attempts before ban
    $ban_time    = 24;    // ban hours
    $time_out    = 900;   // number of seconds before session timeout (since last active)
    $max         = 86400; // maximum length of login (even with activity)
        // --- end modifiable variables ---
    $message     = ''; // placeholder for login error/status messages
        // If you don't want to use the cookie/phpsessionid, then replace that with some unique string. 
        // It is only used to provide a pseudo-namespace for the session login details (unique value per user/session):
    if(!isset($_COOKIE['PHPSESSID'])) { // check that we can actually use the cookie as the id for authorization 
        !isset($_SESSION['cookie_try_count'])? $_SESSION['cookie_try_count'] = 1 : $_SESSION['cookie_try_count']++;
        if($_SESSION['cookie_try_count'] > 1) { header('HTTP/1.0 418 I\'m a teapot'); exit('<h1>418 I\'m a Teapot</h1>Cookies are required in order to complete this service.'); }
        else { header('location: '.$_SERVER['REQUEST_URI']); exit; } // Retry once
    }
    if(@$_SESSION[$_COOKIE['PHPSESSID']]['auth']['ban_time'] && $_SESSION[$_COOKIE['PHPSESSID']]['auth']['ban_time'] > time()) exit; // this is not very secure
    if(isset($_GET["logout"])) LOGGED_IN(0); // log out
    if(isset($_REQUEST["login"])) LOG_IN(@$_POST['login'],@$_POST['password']); // log in
    if(!LOGGED_IN($time_out, $max)) SHOW_LOGIN();
    function LOG_IN($u,$p) {
        global $credentials,$max_logins,$ban_time;
        unset($_SESSION[$_COOKIE['PHPSESSID']]['auth']['fail_count']);
        if(isset($credentials[hash('SHA256',$salt.trim($u))]) && @$credentials[hash('SHA256',$salt.trim($u))] == hash('SHA256',$salt.trim($p))) { // good login
            $_SESSION[$_COOKIE['PHPSESSID']]['auth']['last_seen'] = time();
            $_SESSION[$_COOKIE['PHPSESSID']]['auth']['login_time'] = time();
            $_SESSION[$_COOKIE['PHPSESSID']]['auth']['login'] = trim($u);
            unset($_SESSION[$_COOKIE['PHPSESSID']]['auth']['fail_count'], $_SESSION[$_COOKIE['PHPSESSID']]['auth']['message']);
            return true;
        } // otherwise invalid login, check # attempts/ban:
        if(!isset($_SESSION[$_COOKIE['PHPSESSID']]['auth']['fail_count'])) $_SESSION[$_COOKIE['PHPSESSID']]['auth']['fail_count'] = 0;
        if(++$_SESSION[$_COOKIE['PHPSESSID']]['auth']['fail_count'] < $max_logins) $_SESSION[$_COOKIE['PHPSESSID']]['auth']['message'] = "Invalid login! Remaining opportunities: ".($max_logins - $_SESSION[$_COOKIE['PHPSESSID']]['auth']['fail_count']).'/'.$max_logins;
        else $_SESSION[$_COOKIE['PHPSESSID']]['auth']['ban_time'] = time() + $ban_time * 3600;
        SHOW_LOGIN();
    }
    function SHOW_LOGIN() {
        exit ('<html><head><style class="text/css">
             body { margin: 0; display: flex; background: linear-gradient(to right, rgba(117,189,209,0.5) 0%, rgba(193,234,191,0.7) 100%), linear-gradient(to bottom, rgba(147,206,222,0) 0%, rgba(117,189,209,1) 41%, rgba(73,165,191,0.6) 100%); }
             form { display: flexbox; margin: auto auto; vertical-align: middle; padding: 20px 30px; border-radius:10px; background: rgba(255,255,255,0.75); text-align: right; filter: drop-shadow(15px 10px 6px rgba(0,40,40,0.2)); } 
             p,input { display: block; font-family: sans-serif; margin: 0 auto; }
             input { margin: 5px 0px; padding: 5px 8px; }
             input[type=text],input[type=password],input[type=submit] { border: 1px solid rgba(0,0,0,0.4); width: 100%; }
             p,input[type=submit] { color: rgba(0,0,0,0.7); width: auto; } 
             input[type=submit] { margin-left: auto; margin-right: 0; padding: 5px 25px; } 
            </style></head>
            <body><form method="POST" name="login">
              <p>'.$_SESSION[$_COOKIE['PHPSESSID']]['auth']['message'].'</p>
              <input type="hidden" name="login" value="login" /><input type="text" name="login" />
              <input type="password" name="password" /><input type="submit" value="Log in..." />
            </form></body></html>');
    }
    function LOGGED_IN($time_out=180, $max=86400) {
        if(@$_SESSION[$_COOKIE['PHPSESSID']]['auth']['login_time'] > 9999999 && 
            time() - @$_SESSION[$_COOKIE['PHPSESSID']]['auth']['last_seen'] < $time_out && 
            time() - @$_SESSION[$_COOKIE['PHPSESSID']]['auth']['login_time'] < $max ) {
            $_SESSION[$_COOKIE['PHPSESSID']]['auth']['last_seen'] = time();
            return true;
        } else {
            if(!isset($_SESSION[$_COOKIE['PHPSESSID']]['auth']['login_time'])) $_SESSION[$_COOKIE['PHPSESSID']]['auth']['message'] = 'You need to log in to access this resource.'; // new login
            else if($timeout == 0) $_SESSION[$_COOKIE['PHPSESSID']]['auth']['message'] = 'You have been logged out successfully.'; // log out
            else $_SESSION[$_COOKIE['PHPSESSID']]['auth']['message'] = 'Session expired. Please log in again.'; // time out
            $_SESSION[$_COOKIE['PHPSESSID']]['auth']['url'] = $_SERVER['REQUEST_URI'];
        }
        unset($_SESSION[$_COOKIE['PHPSESSID']]['auth']['last_seen'], $_SESSION[$_COOKIE['PHPSESSID']]['auth']['login_time']);
        if($time_out == 0) { header('location: '.$_SERVER['PHP_SELF']); exit; }
        return false;
    }
    // ----------------- End Login Section (add protected content after this line) -----------------
    echo '<h4>This content is protected.</h4><a href="?logout">log out...</a>';
?>

Even in 2023, I find myself writing small PHP scripts for debug logging and other testing tasks that I'd rather keep behind some sort of protection, so here's a login script that will let you do all that. It's on GitHub at https://github.com/Mugane/simple-php-auth

<?php
    /* 
       Login system in a single php file.
       Tabs, obviously; Configurable editors exist for those with spacing hangups.
       © 2023 Peter Kionga-Kamau. MIT License with this comment block left intact.
       https://github.com/Mugane/simple-php-auth
    */
    // ----------------- Begin Login Section (add protected content after this section) -----------------
    @session_start();
        // --- start modifiable variables: ---
        // $credentials contains unsalted hash for the login "admin" and "password" (replace with your hashed credentials):
        // Generate a hash in bash: echo $(echo -n "texttohash" | sha256sum | cut -d " " -f1)
    $credentials = array('8c6976e5b5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918' => '5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8');
    $salt        = '';    // add random string here to salt your password hashes (vaguely more secure)
    $max_logins  = 5;     // maximum number of failed login attempts before ban
    $ban_time    = 24;    // ban hours
    $time_out    = 900;   // number of seconds before session timeout (since last active)
    $max         = 86400; // maximum length of login (even with activity)
        // --- end modifiable variables ---
    $message     = ''; // placeholder for login error/status messages
        // If you don't want to use the cookie/phpsessionid, then replace that with some unique string. 
        // It is only used to provide a pseudo-namespace for the session login details (unique value per user/session):
    if(!isset($_COOKIE['PHPSESSID'])) { // check that we can actually use the cookie as the id for authorization 
        !isset($_SESSION['cookie_try_count'])? $_SESSION['cookie_try_count'] = 1 : $_SESSION['cookie_try_count']++;
        if($_SESSION['cookie_try_count'] > 1) { header('HTTP/1.0 418 I\'m a teapot'); exit('<h1>418 I\'m a Teapot</h1>Cookies are required in order to complete this service.'); }
        else { header('location: '.$_SERVER['REQUEST_URI']); exit; } // Retry once
    }
    if(@$_SESSION[$_COOKIE['PHPSESSID']]['auth']['ban_time'] && $_SESSION[$_COOKIE['PHPSESSID']]['auth']['ban_time'] > time()) exit; // this is not very secure
    if(isset($_GET["logout"])) LOGGED_IN(0); // log out
    if(isset($_REQUEST["login"])) LOG_IN(@$_POST['login'],@$_POST['password']); // log in
    if(!LOGGED_IN($time_out, $max)) SHOW_LOGIN();
    function LOG_IN($u,$p) {
        global $credentials,$max_logins,$ban_time;
        unset($_SESSION[$_COOKIE['PHPSESSID']]['auth']['fail_count']);
        if(isset($credentials[hash('SHA256',$salt.trim($u))]) && @$credentials[hash('SHA256',$salt.trim($u))] == hash('SHA256',$salt.trim($p))) { // good login
            $_SESSION[$_COOKIE['PHPSESSID']]['auth']['last_seen'] = time();
            $_SESSION[$_COOKIE['PHPSESSID']]['auth']['login_time'] = time();
            $_SESSION[$_COOKIE['PHPSESSID']]['auth']['login'] = trim($u);
            unset($_SESSION[$_COOKIE['PHPSESSID']]['auth']['fail_count'], $_SESSION[$_COOKIE['PHPSESSID']]['auth']['message']);
            return true;
        } // otherwise invalid login, check # attempts/ban:
        if(!isset($_SESSION[$_COOKIE['PHPSESSID']]['auth']['fail_count'])) $_SESSION[$_COOKIE['PHPSESSID']]['auth']['fail_count'] = 0;
        if(++$_SESSION[$_COOKIE['PHPSESSID']]['auth']['fail_count'] < $max_logins) $_SESSION[$_COOKIE['PHPSESSID']]['auth']['message'] = "Invalid login! Remaining opportunities: ".($max_logins - $_SESSION[$_COOKIE['PHPSESSID']]['auth']['fail_count']).'/'.$max_logins;
        else $_SESSION[$_COOKIE['PHPSESSID']]['auth']['ban_time'] = time() + $ban_time * 3600;
        SHOW_LOGIN();
    }
    function SHOW_LOGIN() {
        exit ('<html><head><style class="text/css">
             body { margin: 0; display: flex; background: linear-gradient(to right, rgba(117,189,209,0.5) 0%, rgba(193,234,191,0.7) 100%), linear-gradient(to bottom, rgba(147,206,222,0) 0%, rgba(117,189,209,1) 41%, rgba(73,165,191,0.6) 100%); }
             form { display: flexbox; margin: auto auto; vertical-align: middle; padding: 20px 30px; border-radius:10px; background: rgba(255,255,255,0.75); text-align: right; filter: drop-shadow(15px 10px 6px rgba(0,40,40,0.2)); } 
             p,input { display: block; font-family: sans-serif; margin: 0 auto; }
             input { margin: 5px 0px; padding: 5px 8px; }
             input[type=text],input[type=password],input[type=submit] { border: 1px solid rgba(0,0,0,0.4); width: 100%; }
             p,input[type=submit] { color: rgba(0,0,0,0.7); width: auto; } 
             input[type=submit] { margin-left: auto; margin-right: 0; padding: 5px 25px; } 
            </style></head>
            <body><form method="POST" name="login">
              <p>'.$_SESSION[$_COOKIE['PHPSESSID']]['auth']['message'].'</p>
              <input type="hidden" name="login" value="login" /><input type="text" name="login" />
              <input type="password" name="password" /><input type="submit" value="Log in..." />
            </form></body></html>');
    }
    function LOGGED_IN($time_out=180, $max=86400) {
        if(@$_SESSION[$_COOKIE['PHPSESSID']]['auth']['login_time'] > 9999999 && 
            time() - @$_SESSION[$_COOKIE['PHPSESSID']]['auth']['last_seen'] < $time_out && 
            time() - @$_SESSION[$_COOKIE['PHPSESSID']]['auth']['login_time'] < $max ) {
            $_SESSION[$_COOKIE['PHPSESSID']]['auth']['last_seen'] = time();
            return true;
        } else {
            if(!isset($_SESSION[$_COOKIE['PHPSESSID']]['auth']['login_time'])) $_SESSION[$_COOKIE['PHPSESSID']]['auth']['message'] = 'You need to log in to access this resource.'; // new login
            else if($timeout == 0) $_SESSION[$_COOKIE['PHPSESSID']]['auth']['message'] = 'You have been logged out successfully.'; // log out
            else $_SESSION[$_COOKIE['PHPSESSID']]['auth']['message'] = 'Session expired. Please log in again.'; // time out
            $_SESSION[$_COOKIE['PHPSESSID']]['auth']['url'] = $_SERVER['REQUEST_URI'];
        }
        unset($_SESSION[$_COOKIE['PHPSESSID']]['auth']['last_seen'], $_SESSION[$_COOKIE['PHPSESSID']]['auth']['login_time']);
        if($time_out == 0) { header('location: '.$_SERVER['PHP_SELF']); exit; }
        return false;
    }
    // ----------------- End Login Section (add protected content after this line) -----------------
    echo '<h4>This content is protected.</h4><a href="?logout">log out...</a>';
?>
提笔书几行 2024-10-08 16:08:01

这并不是最强大的密码保护,因此请不要使用它来保护信用卡号或非常重要的东西。

只需将以下所有代码放入名为(secure.php)的文件中,更改用户并从“admin”传递到您想要的任何内容。然后在包含(“secure.html”)的那些行下,只需将其替换为您希望他们能够看到的文件名。

他们将通过 [YouDomain.com/secure.php] 访问此页面,然后 PHP 脚本将在内部包含您想要受密码保护的文件,这样他们就不会知道该文件的名称,并且以后无法直接访问它绕过密码提示。

如果您想添加进一步的保护级别,我建议您将 (secure.html) 文件放在站点根文件夹 [/public_html] 之外,并将其放置在与该目录相同的级别,以便它不在目录内。然后,在包含该文件的 PHP 脚本中,只需使用 (“../secure.html”)。 (../) 意味着返回一个目录来查找该文件。通过这种方式,某人访问 (secure.html) 页面上的内容的唯一方法是通过 (secure.php) 脚本。

<?php
$user = $_POST['user'];
$pass = $_POST['pass'];

if($user == "admin"
&& $pass == "admin")
{
        include("secure.html");
}
else
{
    if(isset($_POST))
    {?>

            <form method="POST" action="secure.php">
            User <input type="text" name="user"></input><br/>
            Pass <input type="password" name="pass"></input><br/>
            <input type="submit" name="submit" value="Go"></input>
            </form>
    <?}
}
?>

Not exactly the most robust password protection here, so please don't use this to protect credit card numbers or something very important.

Simply drop all of the following code into a file called (secure.php), change the user and pass from "admin" to whatever you want. Then right under those lines where it says include("secure.html"), simply replace that with the filename you want them to be able to see.

They will access this page at [YouDomain.com/secure.php] and then the PHP script will internally include the file you want password protected so they won't know the name of that file, and can't later just access it directly bypassing the password prompt.

If you would like to add a further level of protection, I would recommend you take your (secure.html) file outside of your site's root folder [/public_html], and place it on the same level as that directory, so that it is not inside the directory. Then in the PHP script where you are including the file simply use ("../secure.html"). That (../) means go back a directory to find the file. Doing it this way, the only way someone can access the content that's on the (secure.html) page is through the (secure.php) script.

<?php
$user = $_POST['user'];
$pass = $_POST['pass'];

if($user == "admin"
&& $pass == "admin")
{
        include("secure.html");
}
else
{
    if(isset($_POST))
    {?>

            <form method="POST" action="secure.php">
            User <input type="text" name="user"></input><br/>
            Pass <input type="password" name="pass"></input><br/>
            <input type="submit" name="submit" value="Go"></input>
            </form>
    <?}
}
?>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文