如何使用访问代码保护页面


How to secure page with access code

好的,伙计们,我试图用访问代码来保护页面,但如果有些人在url pagename中写入,页面就不会被保护。php页面加载时没有检查我的代码是。代码是在将正确的访问代码重定向到我的页面后工作的,但是,页面在url中写入我的页面之后没有代码就无法保护客户端访问页面。。。。。

 <?php
include ('modules/conf.php');
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST") {
 $secretcode = mysqli_real_escape_string($db,$_POST['secretcode']);
 $sql = "SELECT * FROM password WHERE password = '$secretcode'";
      $result = mysqli_query($db,$sql);
      $row = mysqli_fetch_array($result,MYSQLI_ASSOC);
      $active = $row['active'];
      $count = mysqli_num_rows($result);
      if($count == 1) {
         $_SESSION['login_user'] = $secretcode;
           session_start();
         header("location: question.php");
      }else {
        echo '<script type="text/javascript">';
    echo 'setTimeout(function () { swal("", "Съжеляваме вашият код е невалиден");';
    echo '}, 1000);</script>';
      }
   }
?>
    <div class="section">
        <div class="container-fluid gamebox">
          <div class="row">
          <div class="col-md-6">
            <div class="secretcode">
             <h1 class="text-center">въведете код от брошурата</h1>
             <form action="" method="post" class="formsecretcode text-center">
 <input type="secretcode" id="codeverify" name="secretcode" placeholder="въведете вашият код">
 <input type="submit" class="buttonsubmit" name="submit" value="провери код">
</form>
            </div>
          </div>

正如我在评论中所说,到目前为止还没有人发布答案,我提交了以下内容。

检查会话是否已设置(带有可选的"if { equal to something }"(,如果未设置,则为else { kick them out }

逻辑是,并成为使用您希望保护的会话的每个页面的一部分,例如假设$secretcode等于12345:

<?php 
session_start();
if (isset($_SESSION['login_user']) && $_SESSION['login_user'] == '12345'){
   // Do something
}
else {
   // Do something else
}

最好在头之后添加exit;,否则您的代码可能需要继续执行。

参考:

  • http://php.net/manual/en/function.header.php

脚注:

您不需要使用session_start();两次,因为这可能会触发会话已经启动。

  • 在每页的"顶部"使用一次,同时确保在页眉之前没有输出

参考文献:

  • http://php.net/manual/en/features.sessions.php

  • 如何修复";标头已发送";PHP 中的错误


错误报告添加到文件顶部,这将有助于查找错误。

<?php 
error_reporting(E_ALL);
ini_set('display_errors', 1);
// Then the rest of your code

旁注:显示错误只能在暂存中进行,而不能在生产中进行。


附加说明:

您可以选择在查询中同时检查用户名和密码,这会使查询更加独特。

$username = "Johnny B. Good";
$sql = "SELECT * FROM password 
        WHERE username = '$username' 
        AND password = '$secretcode'";

除非您只检查一个密码,否则请保持查询的原样。