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