首页 > 解决方案 > 单击注销按钮刷新php中的页面

问题描述

我创建了一个页面作为 index.php 并添加了登录代码。它对我来说工作正常,但是当我单击注销按钮时,它正在刷新页面,如果我直接输入 URL,就像localhost/sample/testing.php我没有登录时它正在打开一样。用户在登录之前无法访问任何页面。这是我编写的代码。我使用静态数据登录,因为没有数据库。

索引.php

<?php
 session_start();
 $userinfo = array(
            'user1'=>'password1',
            'user2'=>'password2'
            );
if(isset($_GET['logout'])) {
  $_SESSION['username'] = '';
  header('Location:  ' . $_SERVER['PHP_SELF']);
}
if(isset($_POST['username'])) {
  if($userinfo[$_POST['username']] == $_POST['password']) {
      $_SESSION['username'] = $_POST['username'];
      header("Location:  dashboard.php");
  }else {
     header("Location:  index.php");
  }
}
?>

边栏.php

<?php if($_SESSION['username']): ?>
<ul>
    <li class="dropdown profile_details_drop">
        <a href="#" class="dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
            <div class="profile_img">
                <div class="user-name">
                    <p><a href="?logout=1">Logout</p>
                </div>
                <div class="clearfix"></div>
            </div>
        </a>
    </li>
</ul>
<?php endif; ?>

如果任何用户没有登录,那么他们也可以看到内页。他们在登录之前无法看到该页面。

标签: php

解决方案


你已经设置了$_SERVER['PHP_SELF']。这就是它重定向到同一页面的原因。你需要改变它,例如:login.php

if(isset($_GET['logout'])) {
  unset($_SESSION['username']);// do not set it as empty, unset it
  //header('Location:  ' . $_SERVER['PHP_SELF']);//change this line to
 header('Location:  login.php');
}

另一个错误是在您的 else 条件下,您将其重定向到index.php这就是未登录用户能够看到索引页面的原因。

else {
  //header("Location:  index.php");// change this to
  header('Location:  login.php');
}

注意:我只添加login.php了例如。将未登录的用户重定向到您想要的位置。


推荐阅读