Capturing the Referrer to Redirect After Login
The pattern of allowing users to browse content, click a login prompt, and then returning them to that specific piece of content upon authentication is a standard UX requirement. The core challenge lies not in the authentication logic itself, but in capturing the URL of the page the user intended to visit before they were interrupted by the login form.
In the scenario described, login.php presents a simple form submitting to login-check.php. The current implementation relies on query parameters (?p=1, ?p=2, etc.) to handle error states and redirect authenticated users to index.php. This approach is functionally sound for displaying messages but fails to capture the user's intended destination.
To fix this, you need to capture the HTTP Referrer header. When a user clicks a link or submits a form from another page (e.g., post-detail.php), the browser automatically includes the URL of that previous page in the Referer header sent with the request to login.php. You can access this data using the $_SERVER['HTTP_REFERER'] superglobal.
Here is how to modify login.php to capture and store this information:
<?php
session_start();
// Capture the referrer immediately when the page loads
$redirect_url = $_SERVER['HTTP_REFERER'] ?? '/'; // Default to home if no referrer exists
// Render the login form with a hidden input that passes the URL back
?>
<form method="post" action="login-check.php">
<input type="hidden" name="redirect_to" value="<?php echo htmlspecialchars($redirect_url); ?>">
<!-- Username and password inputs here -->
<input type="text" name="username" placeholder="Username">
<input type="password" name="password" placeholder="Password">
<button type="submit">Login</button>
</form>
By including a hidden input named redirect_to, you pass the target URL back to the validation script. This decouples the redirect logic from the session state or error codes, making it more robust.
Next, update login-check.php to retrieve this value and store it in the session before performing any authentication checks. Storing it in the session ensures that even if the user is forced to reload the page after an error, the original destination remains intact.
<?php
session_start();
// Capture the intended redirect URL from the hidden form field or default to index
$redirect_url = $_POST['redirect_to'] ?? '/index.php';
// Store in session to persist across redirects if necessary (e.g., during error handling)
$_SESSION['intended_destination'] = $redirect_url;
// Proceed with existing authentication logic...
if(empty($username) OR empty($password) AND !isset($_SESSION['id_login'])) {
header("Location:login.php?p=1");
exit();
} elseif (!user_exists($username,$password) AND !isset($_SESSION['id_login'])) {
// Note: The source material says "User exists" for error 2,
// but standard logic checks if user does NOT exist. Adjust based on your actual DB check.
header("Location:login.php?p=2");
exit();
} elseif(isset($_SESSION['id_login'])) {
header("Location:login.php?p=3");
exit();
}
// Logic to actually log the user in goes here...
// Once logged in, redirect to the stored destination
header("Location: " . $_SESSION['intended_destination']);
exit();
?>
Handling Edge Cases and Pitfalls
While capturing $_SERVER['HTTP_REFERER'] is straightforward, it introduces specific edge cases you must account for.
First, security-conscious browsers or certain ad blockers often strip the Referer header. If a user accesses your login form directly via a bookmark or by typing the URL, $_SERVER['HTTP_REFERER'] will be empty. The code above handles this gracefully by defaulting to /index.php, but you should ensure your application has a sensible fallback for these scenarios.
Second, consider the security implications of blindly trusting the referrer. In most login flows, users expect to return to the page they came from. However, if an attacker tricks a user into clicking a malicious link that sends their session back to login.php with a fake referrer header pointing to a sensitive admin dashboard, you must ensure your redirect logic validates the destination. Ideally, restrict redirects to pages on your own domain or specific whitelisted URLs before performing a Location header redirect.
Finally, be wary of infinite loops. In the original code, error states (?p=1, ?p=2) redirect back to login.php. If the form is empty and it redirects to login.php?p=1, ensure that login.php handles the query parameter correctly without immediately submitting a new POST request that might trigger the logic again. The provided solution separates the message display (via GET) from the submission logic (POST), which naturally prevents loops.
For developers building more complex applications, frameworks like Laravel handle this referrer capture and redirect logic internally within their authentication guards, abstracting away the $_SERVER superglobals and session manipulation into a cleaner syntax. If you are using such a framework, reviewing its documentation on session configuration is often the most efficient path forward.
