0

Edit: Implemented new code. It work but it doesn't tackle the page that has ?id= at the end.

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:

<?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>";
}

}
?>
Lim
  • 39
  • 8
  • Okay you are looking to have a user with a specific ID log back in and then have them redirected to the page they were in when they logged off? correct? Do you store the ID in a data base or do you have a user ID set in your DB or a key that is being used to locate this user? – dale landry Mar 20 '20 at 03:09
  • If so you could add an entry into the DB that saves the page they were in when they log out. Then once they log back in grab that from the DB. This would mean querying the DB when the user logs off and entering that page data into a table, then when they log in, grab that page and then set the redirect URL `$target_page` and maybe an extra `$sessPage` into the $url string that will parse into `header()`. – dale landry Mar 20 '20 at 03:12

2 Answers2

1

Use a header() redirect in your successful update conditional 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;
}

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" }. 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. 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 }.

SESSIONS Create a session and store relevant info there like 'userLoggedIn' which would be set at the user login pages successful log in.

 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:

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

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. Set this in php and call in your 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.

// 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;
    }
}
dale landry
  • 7,831
  • 2
  • 16
  • 28
  • May I ask if I want it to direct to non specific page (As in the user wants to go to somewhere else but the website detect they are not logged in so they had to log in to be able to redirect back to they want to go, if not they will go to the default direct page which is myprofile.php) where can I modify? – Lim Mar 11 '20 at 07:55
  • This would deal with correct session handling in your code. You would need to have session handling in each of your restricted pages to check if the user is in fact logged in and if not then redirect them to login page or where ever you wish, perhaps the sites index page. – dale landry Mar 11 '20 at 22:54
  • So I've managed to get a simpler one from gilbertdim, but! `$_SERVER['PHP_SELF'];` doesn't tackle is `?id=` of the page Does your code tackle it? – Lim Mar 12 '20 at 08:00
  • All `$_SERVER['PHP_SELF']` does is get the filename of the currently executing script, relative to the document root. For instance, `$_SERVER['PHP_SELF']` in a script at the address `http:// mysite.com/pages/contact.php` would be `/pages/contact.php`. Then add your key/value url post `?id=`. – dale landry Mar 12 '20 at 20:54
  • The code I provided for a session is an example. My suggestion is to read up on SESSIONS thoroughly so you can gain a better understanding of how they work. Set your session on a login page or login check page and then add code on protected pages that you wish to only show those who are logged in. Use your headers to redirect when session handling is done. – dale landry Mar 12 '20 at 20:57
  • @Lim see my updated example, should shine more light on your issue. – dale landry Mar 20 '20 at 04:17
  • I've successfully done it, thank you very much for the help – Lim Mar 20 '20 at 04:52
1

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

<!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

<?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');
   }
gilbertdim
  • 357
  • 2
  • 11
  • I'm facing some internal server error, can you look at the latest edited code I've edited in my question to see where is the problem? – Lim Mar 12 '20 at 03:20
  • try to store the $_SESSION['last_page'] into a variable then unset the session 'last_page' – gilbertdim Mar 12 '20 at 03:40
  • the error may cause of the $_SERVER['PHP_SELF'] value, try to remove the base folder instead of using the whole path – gilbertdim Mar 12 '20 at 03:49
  • Okay, I found where the error of my Internal Server Error is. But where to find the ParentPath through the domain website? – Lim Mar 12 '20 at 04:58
  • after clearing the Internal Server Error does the previous code version work? Examine the $_SERVER['PHP_SELF'] and do some trimming. – gilbertdim Mar 12 '20 at 05:03
  • It still send the user back to the myprofile.php instead of the PHP_SELF link – Lim Mar 12 '20 at 05:05
  • I've found the problem, thank you very much for the help! – Lim Mar 12 '20 at 06:16
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/209502/discussion-between-lim-and-gilbertdim). – Lim Mar 12 '20 at 07:04
  • Solved `$_SESSION['last_page'] = $_SERVER['PHP_SELF'].'?id='.$_GET['id'];` – Lim Mar 12 '20 at 08:51