Перенаправить пользователя на страницу, на которой он остановился после входа в систему. - PullRequest
0 голосов
/ 11 марта 2020

Редактировать: Реализован новый код. Это работает, но не затрагивает страницу с ?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');
    } 
?>

Учитывая логин. 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>";
}

}
?>

Ответы [ 2 ]

1 голос
/ 11 марта 2020

Вам нужно сохранить текущую страницу в сеансе перед перенаправлением на страницу входа.

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

<!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');
   }
1 голос
/ 11 марта 2020

Используйте перенаправление header() в условном успешном обновлении if / else stmt.

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" }. Затем опубликуйте эту переменную, где вы будете sh, чтобы опубликовать ваши сообщения об успехе / ошибке.

Вы можете использовать тот же редирект и добавлять разные пары ключ / значение POST в URL и просеивать результат POST. , Таким образом, вместо ?success вы можете поместить что-то вроде ?error=login, а затем обработать эту ошибку с помощью условия, которое проверяет, установлено ли значение $ _GET ['error'] и = = 'login' if(isset($_GET['login') && $_GET['login' ) === "error"){ //handle error code here and display issue }.

СЕССИИ Создайте сеанс и сохраните в нем соответствующую информацию, такую ​​как '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

РЕДАКТИРОВАТЬ 19 МАРТА 2020 ГОДА:

Если у вас есть БД, в которой сохраняются пользовательские данные, создайте таблицу для страницы, на которой они находятся, когда они выходят из системы, назовите ее logout_page или как-то

В вашем html убедитесь, что каждая страница имеет уникальный идентификатор, установленный в теге body, чтобы вы могли вызывать его при установке переменной посещенных страниц, которая будет отправлена ​​в БД при выходе из системы. Установите это значение в 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;
    }
}
...