繁体   English   中英

单击注销按钮刷新PHP页面

[英]Clicking on logout button refreshing the page in php

我已经创建了一个页面为index.php并添加了登录代码。 它对我来说很好用,但是当我单击注销按钮时,它正在刷新页面,如果我直接输入URL(如localhost/sample/testing.php ,则在未登录的情况下也会打开。 用户必须先登录才能访问任何页面。这是我编写的代码。 我使用静态数据登录,因为没有数据库。

Index.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");
  }
}
?>

Sidebar.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; ?>

如果没有任何用户登录,那么他们也可以看到内部页面。 他们只有登录才能看到页面。

您已经设置了$_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 将未登录的用户重定向到您想要的位置。

首先,应该美化您的代码。

第二,您忘记了关闭a href标签,因此$_GET语句isset不是true。 因此,通过单击链接,页面将再次检查是否为if(isset($_POST['username'])) ,这是正确的,并且您已重定向标题的原因。

考虑在使用session_destroysession_unset地方制作一个logout.php ,并将用户重定向到login.php ,例如:

logout.php:

<?php
session_start();
session_unset($_SESSION['username']);
session_unset();
session_destroy();
header('Location: login.php');
?>

最后,考虑不使用$_GET ,而是仅由于在URL上不可见的原因而更喜欢$_POST$_SESSION变量。

首先,注销时破坏会话。 并将其重定向到登录页面。 假设index.php是登录页面。

 if(isset($_GET['logout'])) {
     session_start();
     session_destroy();
    header('Location: index.php');
 }

在sidebar.php中,检查会话是否设置。 如果未设置会话,则表示用户未登录。 您可以通过将他们重定向到登录页面来阻止他们访问该页面

 <?php
 session_start();
 if (!isset($_SESSION["username"]))
{  
    header("location: index.php");
 } ?>

 <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> 

在注销时取消会话变量:

unset($_SESSION['username']);

而不是分配给空字符串:

$_SESSION['username'] = '';

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM