I would not use cookies at all.
Method 1
A possible way could be to store the link visited into a session variable and then when the user reaches the login.php page, provide a header redirect to $url given by the session variable.
Paste this code into all your pages on your website or the main container.
<?php
session_start();
$_SESSION['url'] = $_SERVER['REQUEST_URI'];
For the login page you can have:
<?php
session_start(); // needed for sessions.
if(isset($_SESSION['url']))
$url = $_SESSION['url']; // holds url for last page visited.
else
$url = "student_account.php";
header("Location: http://example.com/$url");
Method 2
A simpler solution by far is simply to have:
<hidden name="redirurl" value="<? echo $_SERVER['HTTP_REFERER']; ?>" />
Then redirect to that address once they log in.
However, this is only good if you have a login box on every page.
$_SERVER['REQUEST_URI']
will simply hold the current page. What you want to do is use $_SERVER['HTTP_REFERER']
.
So save the HTTP_REFERER in a hidden element on your form, but also take note on that in the PHP that processes the form you will need some logic that redirects back to the login page if login fails but also to check that the referer is actually your website, if it isn't, then redirect back to the homepage.
Method 3
Another common way to do this is to pass the user's current page to the Login form via a $_GET variable.
change your script so that is also tells the login page to remember where you are:
Note: $_SERVER['REQUEST_URI'] is your current page
header("Location:login.php?location=" . urlencode($_SERVER['REQUEST_URI']));
Now check if it is populated, then send the user to this:
login.php
echo '<input type="hidden" name="location" value="';
if(isset($_GET['location'])) {
echo htmlspecialchars($_GET['location']);
}
echo '" />';
// Will show something like this:
// <input type="hidden" name="location" value="previousPage.php" />
login-check.php
session_start();
// our url is now stored as $_POST['location'] (posted from login.php). If it's blank, let's ignore it. Otherwise, let's do something with it.
$redirect = NULL;
if($_POST['location'] != '') {
$redirect = $_POST['location'];
}
if((empty($username) OR empty($password) AND !isset($_SESSION['id_login']))) {
$url = 'login.php?p=1';
// if we have a redirect URL, pass it back to login.php so we don't forget it
if(isset($redirect)) {
$url .= '&location=' . urlencode($redirect);
}
header("Location: " . $url);
exit();
}
elseif (!user_exists($username,$password) AND !isset($_SESSION['id_login'])) {
$url = 'login.php?p=2';
if(isset($redirect)) {
$url .= '&location=' . urlencode($redirect);
}
header("Location:" . $url);
exit();
}
elseif(isset($_SESSION['id_login'])) {
// if login is successful and there is a redirect address, send the user directly there
if($redirect)) {
header("Location:". $redirect);
} else {
header("Location:login.php?p=3");
}
exit();
}