Reputation: 33
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>";
}
}
?>
Upvotes: 0
Views: 950
Reputation: 8610
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;
}
}
Upvotes: 1
Reputation: 357
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');
}
Upvotes: 1