簡體   English   中英

如果用戶登錄,則自動重定向

[英]Auto redirect if user is logged in

我有兩個頁面: index.phpregister.php 如果用戶是guest ,則可以單擊register.php >轉到該頁面->注冊表單並登錄。 登錄后,他將重定向到index.php。 現在,如果他/她嘗試訪問signup.php ->它們將自動重定向到index.php 我正在使用:

<?php 
   if(!isset($_SESSION['id']))
   {
      //show the form
      ....
   }
   else
   {
      header("Location: index.php");
      exit;
   }
   ?>

但是,出現Cannot modify header information錯誤。 index.phpregister.php是兩個單獨的頁面時,我還能如何使代碼重定向。

我要做的是創建一個名為check_logged.php的單獨文件,該文件包含在您希望阻止的頁面的頂部。 它的作用是檢查是否將此添加到頁面頂部

session_start();
include('php/check_logged.php');

Check_logged.php包含以下內容:

if (!empty($_SESSION['id'])) {
    header('Location: index.php');
    exit;
}

就個人而言,我需要進行第二次檢查,因為在您成功恢復密碼后,我的表單會輸出一條確認消息:

if(!isset($_SESSION['good_message'])){ //check if a confirmation message is set, if no continue to check if the user is logged in.
    if (!empty($_SESSION['id'])) {
        header('Location: index.php');
        exit;
    }
}

這樣,如果您返回登錄頁面並要顯示確認消息,它不會立即重定向您。 我傾向於顯示這樣的消息:

<span class="error"> <?php 
    if( IsSet( $_SESSION[ "message_sent" ] ) )  {
            echo "<p align='center' style='color: #8BA870;';> " . $_SESSION[ "message_sent" ] . "</p>";
            unset( $_SESSION[ "message_sent" ] );
}?></span>

它會顯示一次,然后自動取消設置。 因此,如果刷新頁面,則該值不再“設置”,您將被重定向到主頁。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM