简体   繁体   English

将用户重定向到他们登录后离开的页面

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

Edit: Implemented new code.编辑:实施了新代码。 It work but it doesn't tackle the page that has ?id= at the end.它可以工作,但它不处理末尾带有?id=的页面。

Is there any other way to solve this kind of problem?有没有其他方法可以解决此类问题?

Given the snippet to detect if the user is logged in at every page is this:鉴于检测用户是否在每个页面都登录的片段是这样的:

<?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');
    } 
?>

Given the login.php code is this:鉴于 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>";
}

}
?>

Use a header() redirect in your successful update conditional if/else stmt.在成功更新条件 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;
}

Don't forget to add an if(isset($_GET['success'])){ $success = "Your success message here" } on your target page and if(isset($_GET['log_error'])){ $log_error = "Your login error message here" } .不要忘记在目标页面上添加if(isset($_GET['success'])){ $success = "Your success message here" }if(isset($_GET['log_error'])){ $log_error = "Your login error message here" } . Then post that variable where you wish to post your success/error message/'s.然后将该变量发布到您希望发布成功/错误消息的位置。

You can use the same redirect and add different POST key/value pairs to the URL and sift through the POST result.您可以使用相同的重定向并将不同的 POST 键/值对添加到 URL 并筛选 POST 结果。 So instead of ?success , you could put something like ?error=login then handle that error with a conditional that checks if the $_GET['error'] is set and = to 'login' if(isset($_GET['login') && $_GET['login' ) === "error"){ //handle error code here and display issue } .因此,代替?success ,您可以输入类似?error=login然后使用条件处理该错误,该条件检查是否设置了 $_GET['error'] 并且 = 为 'login' if(isset($_GET['login') && $_GET['login' ) === "error"){ //handle error code here and display issue } .

SESSIONS Create a session and store relevant info there like 'userLoggedIn' which would be set at the user login pages successful log in. 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

EDIT MARCH 19, 2020: 2020 年 3 月 19 日编辑:

If you have a DB that saves user data create a table for the page they are on when they logout, call it logout_page or something如果您有一个保存用户数据的数据库,则为他们注销时所在的页面创建一个表,将其logout_page或其他名称

In your html make sure each page has a unique ID set in the body tag so you can call on that when setting past page visited variable that will be sent to DB when they log out.在您的 html 中,确保每个页面在 body 标签中设置了一个唯一的 ID,这样您就可以在设置过去页面访问变量时调用它,该变量将在他们注销时发送到 DB。 Set this in php and call in your html.在 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 
}

When the user logs in alter the login script and include the last_page to your results query.当用户登录时,更改登录脚本并将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;
    }
}

What you need to do is save the current page in session before redirecting to sign in page.您需要做的是在重定向到登录页面之前将当前页面保存在会话中。

myprofile.php我的配置文件

<?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');

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 - post request validation 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