如何防止 PHP SESSION 在页面刷新时关闭?

How to prevent PHP SESSION closing when the page is refreshed?

我已经为我的画廊网站创建了注册和登录系统。当用户尝试登录系统时,将检查他们的用户名和密码以及管理员权限。如果成功,用户名将出现在主页的左上角,登录变为注销。问题是当我刷新页面时,用户已注销。

login.php代码:

<?php

session_start();

class User

{

    public function CheckUser()

    {

        require "../app/core/database.php";

        if (isset($_POST['username']) && isset($_POST['pass'])) {

            $username = $_POST['username'];

            $password = $_POST['pass'];

            //to prevent sql injection

            $username = stripcslashes($username);

            $password = stripcslashes($password);

            $username = mysqli_real_escape_string($connection, $username);

            $password = mysqli_real_escape_string($connection, $password);

            $sql = "SELECT * FROM signup WHERE username = '$username' and password = '$password'";

            $sql2 = "SELECT 'admin' FROM signup";

            $log_result = mysqli_query($connection, $sql);

            $count = mysqli_num_rows($log_result);

            if ($count == 1) {

                $_SESSION['loggedin'] = true;

                $_SESSION['username'] = $username;

                $_SESSION['is_admin'] = mysqli_query($connection, $sql2);

                header("Location: ../home/index");

            } else {

                echo "<script>Invalid()</script>";

            }

        }

    }

}

?>

<script>

    function Invalid() {

        alert("Invalid user/password");

    }

</script> 

部分首页代码(index.php):

<?php

error_reporting(E_ALL);

ini_set('display_errors', TRUE);

include "../app/model/loadImages.php";

include "../app/core/config.php";

include "../app/model/login.php";

?>

<body>
  <nav>
    <?php while ($row = $result2->fetch_assoc()) {
      $rows[] = $row ?>
      <div class="logo">
        <a href="index.php"><?php echo $row['header_1'] ?> <em><?php echo $row['header_2'] ?></em></a>
        <span style="font-weight: normal; color:white;">
          <label>
            <?php
            if (isset($_SESSION['loggedin']) && isset($_SESSION['username'])) {
              echo $_SESSION['username'];
            } ?>
          </label>
        </span>
      </div>
      <div class="menu-icon">
        <span></span>
      </div>
      </nav>
 <section class="overlay-menu">
    <div class="container">
      <div class="row">
        <div class="main-menu">
          <ul>

            <li>
              <?php
              if (!isset($_SESSION['loggedin']) && !isset($_SESSION['username'])) {
                echo "<a href='/MyProject/public/login/index.php'>LogIn</a>";
              } else {
                echo "<a href='' action='EndSession();'>Logout</a>";
                echo "<li>";
                echo "<a href='/MyProject/public/admin/index'>Admin Area</a>";
                echo "</li>";
              } ?>

            </li>
            <li>
              <a href="about.html">About Us</a>
            </li>
            <li>
              <a href="blog.html">Blog Entries</a>
            </li>
            <li>
              <a href="single-post.html">Single Post</a>
            </li>
          </ul>
          <?php foreach ($rows as $row) { ?>
            <p><?php echo $row['message_1'] ?></p>
          <?php } ?>
        </div>
      </div>
    </div>
  </section>
<script>
    function EndSession() {

      <?php session_unset(); ?>
    }
  </script>

index.php 登录页面:

<?php
include "../app/core/config.php";
include "../app/model/login.php";

$login = new User();
$login->CheckUser();

?>

<body>
    
    <div class="limiter">
        <div class="container-login100" style="background-image: url('../../app/views/login/images/bg-01.jpg');">
            <div class="wrap-login100 p-l-55 p-r-55 p-t-65 p-b-54">
                <form class="login100-form validate-form" method="POST">
                    <span class="login100-form-title p-b-49">
                        Login
                    </span>

                    <div class="wrap-input100 validate-input m-b-23" data-validate = "Username is reauired">
                        <span class="label-input100">Username</span>
                        <input class="input100" type="text" name="username" placeholder="Type your username">
                        <span class="focus-input100" data-symbol="&#xf206;"></span>
                    </div>

                    <div class="wrap-input100 validate-input" data-validate="Password is required">
                        <span class="label-input100">Password</span>
                        <input class="input100" type="password" name="pass" placeholder="Type your password">
                        <span class="focus-input100" data-symbol="&#xf190;"></span>
                    </div>
                    
                    <div class="text-right p-t-8 p-b-31">
                        <a href="#">
                            Forgot password?
                        </a>
                    </div>
                    
                    <div class="container-login100-form-btn">
                        <div class="wrap-login100-form-btn">
                            <div class="login100-form-bgbtn"></div>
                            <button class="login100-form-btn">
                                Login
                            </button>
                        </div>
                    </div>

                    <div class="txt1 text-center p-t-54 p-b-20">
                        <span>
                            Or Sign Up Using
                        </span>
                    </div>

                    <div class="flex-c-m">
                        <a href="#" class="login100-social-item bg3">
                            <i class="fa fa-google"></i>
                        </a>
                    </div>

                    <div class="flex-col-c p-t-155">
                        <span class="txt1 p-b-17">
                            Or Sign Up Using
                        </span>

                        <a href="<?php echo $root ?>/public/signup/index.php" class="txt2">
                            Sign Up
                        </a>
                    </div>
                </form>
            </div>
        </div>
    </div>

我该如何解决这个问题?

我重现了这个问题。 js函数里面的session_unset是在刷新页面的时候调用的,而且是在一个JS函数里面。

删除该函数,然后创建一个名为 logout.php:

的新文件
<?php 
session_unset();
header("Location: ../home/index.php");
?>

修改home/index里面的a标签。php:

<a href='logout.php'>Logout</a>

旁注:考虑使用 session_destroy() 而不是 session_unset() 注销

你必须创建session和setcookie,这个方法希望对你有帮助

首先select验证用户: 如果您使用 bcrypt 算法

存储密码,则 password_verify 功能有效
  <?php
    if(isset($_POST["username"])) {
        $u = $dbmysqli->real_escape_string($_POST['username']);
        $p = $_POST['p'];



        $sql = $dbmysqli->prepare('SELECT username, password FROM users WHERE username = ?');
        $sql->bind_param("s", $u);
        $sql->execute();
        $sql->store_result();
    }
    if ($sql->num_rows > 0) {
        $sql->bind_result($db_id, $db_username, $db_pass_str);
        $sql->fetch();
        if (password_verify($p, $db_pass_str)) {
            // Verification success! User has logged-in!
            // Create sessions, so we know the user is logged in, they basically act like cookies but remember the data on the server.
            session_regenerate_id(TRUE);
            $_SESSION['userid'] = $db_id;
            $_SESSION['username'] = $db_username;
            $_SESSION['password'] = $db_pass_str;
            setcookie("id", $db_id, strtotime('+30 days'), "/", "", "", TRUE);
            setcookie("user", $db_username, strtotime('+30 days'), "/", "", "", TRUE);
            setcookie("pass", $db_pass_str, strtotime('+30 days'), "/", "", "", TRUE);
            echo $db_username;
            exit();
        } else {
            // Incorrect password
            echo 'login_failed';
        }
    }
    ?>

然后你必须像这样创建一个检查登录状态file.php(如果你想让用户保持登录状态,请在每个页面中包含这个):

<?php
$user_ok = FALSE;
$log_id = "";
$log_username = "";
$log_password = "";

function evalLoggedUser($dbmysqli,$id,$u,$p){
    $sql = $dbmysqli->prepare('SELECT email FROM users WHERE id = ? AND uname = ? AND pswd = ?');
    $sql->bind_param("sss", $id,$u,$p);
    $sql->execute();
    $sql->store_result();
    $numrows = $sql->num_rows;
    if($numrows > 0){
        return true;
    }
}

if(isset($_SESSION["userid"]) && isset($_SESSION["username"]) && isset($_SESSION["password"])) {
    $log_id = preg_replace('#[^0-9]#', '', $_SESSION['userid']);
    $log_username = preg_replace('#[^a-z0-9]#i', '', $_SESSION['username']);
    $log_password = $_SESSION['password'];
    //$log_password = preg_replace('#[^a-z0-9$./]#i', '', $_SESSION['password']);

    $user_ok = evalLoggedUser($dbmysqli,$log_id,$log_username,$log_password);
} else if(isset($_COOKIE["id"]) && isset($_COOKIE["user"]) && isset($_COOKIE["pass"])){
    $_SESSION['userid'] = preg_replace('#[^0-9]#', '', $_COOKIE['id']);
    $_SESSION['username'] = preg_replace('#[^a-z0-9]#i', '', $_COOKIE['user']);
    $_SESSION['password'] = $_COOKIE['pass'];
    //$_SESSION['password'] = preg_replace('#[^a-z0-9$./]#i', '', $_COOKIE['pass']);
    $log_id = $_SESSION['userid'];
    $log_username = $_SESSION['username'];
    $log_password = $_SESSION['password'];

    $user_ok = evalLoggedUser($dbmysqli,$log_id,$log_username,$log_password);
    if ($user_ok == TRUE);
}
?>

最后 logout.php :

<?php
session_start();
$_SESSION = array();
if(isset($_COOKIE["id"]) && isset($_COOKIE["user"]) && isset($_COOKIE["pass"])) {
    setcookie("id", '', strtotime( '-5 days' ), '/');
    setcookie("user", '', strtotime( '-5 days' ), '/');
    setcookie("pass", '', strtotime( '-5 days' ), '/');
}
session_destroy();
if(isset($_SESSION['username'])){
    header("location: message.php?msg=Error:_Logout_Failed");
} else {
    header("location: login.php");
    exit();
}
?>