簡體   English   中英

將用戶重定向到他們登錄后離開的頁面

[英]Redirect User to the page they've left off once they had log in

編輯:實施了新代碼。 它可以工作,但它不處理末尾帶有?id=的頁面。

有沒有其他方法可以解決此類問題?

鑒於檢測用戶是否在每個頁面都登錄的片段是這樣的:

<?php
    session_start();
    error_reporting(0);
    include('includes/config.php');
    include('includes/config1.php');

    if(strlen($_SESSION['emplogin'])==0){
        $_SESSION['last_page'] = $_SERVER['PHP_SELF'];
        header('location:../login.php');
    } 
?>

鑒於 login.php 代碼是這樣的:

<?php
session_start();
error_reporting(0);
include('includes/config.php');

if(isset($_POST['signin']))
{
    //sign in code

if($status==0)
{
    $msg="Your account is Inactive. Please contact admin";

} else{
    if(isset($_SESSION['last_page'])) {
        $last_page = $_SESSION['last_page'];
        header("Location: $last_page");
// And remember to clean up the session variable after
// this is done. Don't want it lingering.
        unset($_SESSION['last_page']);
    }else{echo "<script type='text/javascript'> document.location = 'login.php'; </script>";}

} 
}

else{
  echo "<script>alert('Invalid Details');</script>";
}

}
?>

在成功更新條件 if/else stmt 中使用header()重定向。

if($query->rowCount() > 0)
{
    foreach ($results as $result) {
        $status = $result->Status;
        $_SESSION['eid'] = $result->id;
        $_SESSION['name'] = $result->FirstName . " " . $result->LastName;
        $_SESSION['emplogin'] = $result->emp_username;
    }

    if($status == 0)
    {
        $target_page = 'myprofile.php'; // I assume this is the page you are redirecting to 
                                    // on success, change this to your desired link if not.

        //Build your entire http path URL. 
        $url = 'http://' . $_SERVER['HTTP_HOST']; // Get the server
        $url .= rtrim(dirname($_SERVER['PHP_SELF']), '/\\'); // Get the current directory
        $url .= $target_page.'?success';  // <-- Your relative path with a success post through url            
        header('Location: ' . $url, true, 302);
        exit;
    } else {
        echo "<script type='text/javascript'> document.location = 'myprofile.php'; </script>";
    }

} else {
    //else $query->rowCount() !> 0 ***no results...*** 
    $target_page = 'myprofile.php'; 
    $url = 'http://' . $_SERVER['HTTP_HOST']; // Get the server
    $url .= rtrim(dirname($_SERVER['PHP_SELF']), '/\\'); // Get the current directory
    $url .= $target_page.'?log_error';  // <-- Your relative path with an error post through url, handle $_GET['log_error'] on another page or this page and redirect.          
    header('Location: ' . $url, true, 302);
    exit;
}

不要忘記在目標頁面上添加if(isset($_GET['success'])){ $success = "Your success message here" }if(isset($_GET['log_error'])){ $log_error = "Your login error message here" } . 然后將該變量發布到您希望發布成功/錯誤消息的位置。

您可以使用相同的重定向並將不同的 POST 鍵/值對添加到 URL 並篩選 POST 結果。 因此,代替?success ,您可以輸入類似?error=login然后使用條件處理該錯誤,該條件檢查是否設置了 $_GET['error'] 並且 = 為 'login' if(isset($_GET['login') && $_GET['login' ) === "error"){ //handle error code here and display issue } .

SESSIONS創建一個會話並將相關信息存儲在那里,例如“userLoggedIn”,這將在用戶登錄頁面成功登錄時設置。

 session_start();// Start the session
 // $_SESSION['sessData'] is an array that carries pertinent SESSION info that can be 
 // logged through $_SESSIONS within your user login pages
 $sessData = !empty($_SESSION['sessData'])?$_SESSION['sessData']:'';
 // check to see if the user is logged in, if so send them to the restricted 
 // home page for logged in users
 if( isset($_SESSION['userLoggedIn'])!="" ){
    header("Location: home.php"); // home.php is the users logged in page. 
 }
 //handle code if session is not set

2020 年 3 月 19 日編輯:

如果您有一個保存用戶數據的數據庫,則為他們注銷時所在的頁面創建一個表,將其logout_page或其他名稱

在您的 html 中,確保每個頁面在 body 標簽中設置了一個唯一的 ID,這樣您就可以在設置過去頁面訪問變量時調用它,該變量將在他們注銷時發送到 DB。 在 php 中設置它並調用你的 html。

// Declare a variable in your php on each restricted login page the user can access and set it to the following.
// You can use `basename()` and `$_SERVER['PHP_SELF']` to get current page file name.

$pageName = basename($_SERVER['PHP_SELF']);

// conditional to see if user is logging out

if(isset($_GET['logout'])){// $_GET value coming from your logout button that directs to this code        
    //query DB and ad $pageName to your DB entry
    //handle logout 
}

當用戶登錄時,更改登錄腳本並將last_page包含到您的結果查詢中。

// not sure how you connect but it would look similar to this
$sql = "SELECT id, first_name, last_name, email, last_page FROM user_table";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
         //assign values to variables
         $id = $row['id'];
         $target_page = $row['logout_page'];
         // Set sessions here
         $_SESSION['last_page'] = $target_page; 
         $_SESSION['msg'] = "Something you wish to say about logging back and setting to users last page visited";
         // handle unset
         // Build your entire http path URL.

         $optional = '?key=value';// use `?id=` maybe '?id=."$id;
         $url = 'http://' . $_SERVER['HTTP_HOST']; // Get the server
         $url .= rtrim(dirname($_SERVER['PHP_SELF']), '/\\'); // Get the current directory
         $url .= $target_page.$optional;  // <-- Your relative path with a success post through url            
         header('Location: ' . $url, true, 302);
         exit;
    }
}

您需要做的是在重定向到登錄頁面之前將當前頁面保存在會話中。

我的配置文件

<?php
   session_start();

   define('ParentPath', '/stackoverflow/');

   #the value of PHP_SELF in my machine is
   #/stackoverflow/60628661/myprofile.php
   $_SESSION['last_page'] = str_replace(ParentPath, '', $_SERVER['PHP_SELF']);

   if(!isset($_SESSION['User'])) header('Location: signin.php');

登錄.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <form action="check_signin.php" method="post">
        <button type="submit" name="signin">Sign In</button>
    </form>
</body>
</html>

check_signin.php - 發布請求驗證

<?php
   session_start();

   if(isset($_POST['signin'])) {
      $_SESSION['User']['Name'] = 'gilbertdim';
      $_SESSION['User']['Id'] = 1;

      if(isset($_SESSION['last_page'])) {
          $last_page = $_SESSION['last_page'];
          unset($_SESSION['last_page']);

          header("Location: ../$last_page");
      }
   } else {
      header('Location: signin.php');
   }

暫無
暫無

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

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