Simple PHP Post-Redirect-Get Code Example
Post-Redirect-Get (PRG) is a standard web design pattern intended to mitigate issues related to form resubmission and browser navigation behavior. While many resources describe the concept theoretically, implementing it often leads to architectural over-engineering or confusion regarding session management. The core objective is simple: after a POST request processes data, the server must redirect the client to a GET request immediately. This ensures that if the user accidentally hits "Refresh" or clicks the "Back" button, the browser resubmits a GET request to the safe confirmation page rather than replaying the original POST payload.
A robust implementation requires decoupling the processing logic from the response rendering. Consider a scenario where form.php submits data to validate.php. The user never sees validate.php; they only interact with the form and subsequent views. Upon receiving the POST request, validate.php performs all necessary validation checks. If the data fails validation, it generates an error message; if successful, it prepares a confirmation page. Crucially, neither of these HTML responses is echoed immediately to the browser. Instead, both are stored in a server-side session variable, such as $_SESSION['form_html'].
// validate.php logic snippet
if ($validationFailed) {
$response = "<!DOCTYPE html><html><body>...Error details...</body></html>";
} else {
$response = "<!DOCTYPE html><html><body>...Confirmation message...</body></html>";
}
$_SESSION['form_html'] = $response;
header('Location: submitted.php');
exit();
By redirecting to a separate file, such as submitted.php, the application adheres strictly to the PRG pattern. The target URL is a GET request, which browsers cache and allow safe refreshing without side effects. When the browser loads submitted.php, it simply retrieves the previously stored HTML from the session:
// submitted.php content
echo $_SESSION['form_html'];
This approach effectively neutralizes the "double-submit" problem caused by browser back-button history or accidental refreshes on POST responses. The user perceives a seamless transition from input to result, regardless of their navigation attempts after the submission.
However, this pattern introduces specific trade-offs that developers must consider. Storing full HTML pages in $_SESSION can consume memory, particularly if the confirmation page is large or includes heavy assets like embedded images or scripts. For high-traffic applications, generating the response directly on the redirect target is often more performant than persisting it in session storage. If you opt for direct rendering in the destination file, you must ensure that any state required to render the HTML (like the success message) is passed via URL parameters or stored elsewhere, though passing sensitive data via GET parameters should be avoided.
Another critical consideration is session security. Since submitted.php relies on $_SESSION to display content, this endpoint must be protected against unauthorized access. If a user accesses submitted.php without a valid session, they will receive an empty page or a fatal error. Additionally, if the session storage mechanism (like Redis or file-based sessions) is configured with excessive garbage collection times, memory usage may grow unbounded over time.
In modern frameworks like Laravel, this pattern can be implemented cleanly using middleware or controller redirects without manually manipulating sessions for HTML content. You might store the status code or a flash message in the session and render the view based on that flag in the next request. However, the underlying principle remains unchanged: process the POST, redirect immediately, and let the GET request handle the display. This separation of concerns ensures your application remains resilient against common user navigation errors.