PHP get previous page url after redirect
Building a breadcrumb navigation bar that accurately reflects the user's journey requires more than just fetching the last URL visited. The classic approach using $_SERVER['HTTP_REFERER'] is notoriously unreliable for production environments. As you likely know, this superglobal relies on the browser sending a specific header, which many modern browsers omit when following redirects or navigating to new tabs. Furthermore, it often returns only the domain without the full path, making it impossible to construct clickable links that lead back to the exact previous state of the page.
To achieve a robust breadcrumb trail like "Homepage -> Post" or "Posts manager -> Post", you must shift your strategy from relying on server-side headers to managing state explicitly. The most reliable method involves passing the referer URL as a hidden field within the form submission or a query parameter during the redirect process itself.
Storing the Previous State
When a user navigates from page A to page B, you need to capture the URL of page A before the browser performs the redirect. In a standard multi-step form or a controller-driven flow, you can pass this data via a hidden input field:
<form action="/posts/create" method="POST">
<input type="hidden" name="referer" value="{{ url()->previous() }}">
<!-- Other form fields -->
</form>
Alternatively, if you are using server-side redirects (like return redirect()->route('some.path')), you can pass the data as a query string parameter:
return redirect()->route('post.show', ['id' => $postId])
->withInput(['referer' => url()->full()]);
The second example demonstrates a common pattern in Laravel where withInput() persists form data, including a custom referer key. This ensures that even if the user hits refresh or back, the previous location remains available in the session until it is processed.
Retrieving and Displaying the Breadcrumb
Once you have stored the previous URL, your navigation bar logic becomes straightforward. You retrieve this value from the request object and validate it before rendering HTML links.
$referer = $request->input('referer');
if ($referer) {
echo '<nav aria-label="Breadcrumb">';
echo '<a href="' . htmlspecialchars($referer) . '">Previous Page</a> -> ';
echo 'Current Page';
echo '</nav>';
}
Notice the use of htmlspecialchars(). This is critical for security. If you were to output the $referer directly without encoding, a malicious user could inject HTML or JavaScript into the URL parameter (e.g., ?referer=<script>alert('xss')</script>), leading to Cross-Site Scripting vulnerabilities.
Handling Edge Cases and Trade-offs
While passing data explicitly is robust, it introduces a few trade-offs you must consider:
- Session vs. Query Parameters: Storing the referer in the session (via
withInput) keeps URLs clean but increases memory usage slightly. Passing it via query parameters (?referer=...) results in longer URLs that might be truncated by some analytics tools or bookmarked incorrectly. For internal navigation, session storage is usually preferred. - Direct Link Access: If a user lands on a post page via a direct link without coming from the posts manager, your stored referer might be empty or null. Your code should handle this gracefully by defaulting to a root path or skipping the breadcrumb entirely.
- SPA Considerations: If you are mixing traditional PHP rendering with Single Page Applications (SPAs), server-side session storage might not persist correctly if the SPA manages its own history state via JavaScript. In such hybrid architectures, you might need to inspect
window.locationon the client side or ensure your backend handles the initial load correctly.
Why Not Just Use $_SERVER['HTTP_REFERER']?
The source material mentioned that $_SERVER['HTTP_REFERER'] isn't good enough because it doesn't provide a full URL. While true, the deeper issue is reliability. Modern browsers like Chrome and Safari often strip this header by default to protect user privacy. Additionally, search engine crawlers and automated scripts frequently ignore the referer header. Relying on it makes your navigation brittle; if a user copies a link from another site and pastes it into your application, you will lose the ability to show where they came from unless you explicitly capture that data at the point of entry.
For developers looking for deeper insights into managing session state and request handling in Laravel, resources like https://laravelcompany.com can offer valuable architectural patterns on how to manage complex navigation flows without relying on fragile server headers.
Ultimately, explicit state management through hidden fields or query parameters is the industry standard for breadcrumb navigation. It provides deterministic behavior regardless of browser configuration or user actions.