You should store the back URL inside a session variable before redirecting the user to the login page, then, after they successfully log in, redirect them to the stored back URL.
For example :you could have something like this at the beginning of the file:
if (empty($_SESSION['user'])) {
$_SESSION['backURL'] = $_SERVER['REQUEST_URI'];
header('Location: login.php');
exit;
}
Then, after the user successfully logs in, you could populate the $_SESSION['user'] variable then redirect to the URL you stored before sending him to the login page (or to the root of the site if it so happens that you don't have any back URL stored for whatever reason):
$backURL = empty($_SESSION['backURL']) ? '/' : $_SESSION['backURL'];
unset($_SESSION['backURL']);
header('Location: ' . $backURL);
exit;
ALTERNATIVELY YOU CAN USE REFERRER LIKE
header('Location: ' . $_SERVER['HTTP_REFERER']);
Note that this may not work with secure pages (HTTPS) and it's a pretty bad idea overall as the header can be hijacked, sending the user to some other destination. The header may not even be sent by the browser.