Home >Backend Development >PHP Tutorial >How Can I Implement a Simple PHP Post-Redirect-Get (PRG) Pattern?
Simple PHP Post-Redirect-Get (PRG) Code Example
Implementing Post-Redirect-Get (PRG) in PHP can be straightforward. Here's a simplified example:
form.php
<form method="POST" action="validate.php"> <!-- form elements --> </form>
validate.php
<?php if ($_POST) { // Validate input and execute code if (/* valid input */) { // Redirect to itself using REQUEST_URI header("Location: {$_SERVER['REQUEST_URI']}", true, 303); exit(); } }
submitted.php or invalid_input.php
<?php echo $_SESSION['form_html'];
This script generates the form HTML stored in the session and displays it in case the user accesses the URL directly.
Benefits:
Your approach to reinventing the wheel is not unreasonable. However, using the built-in HTTP status codes and header functions can help ensure reliable behavior and interoperability with other applications.
The above is the detailed content of How Can I Implement a Simple PHP Post-Redirect-Get (PRG) Pattern?. For more information, please follow other related articles on the PHP Chinese website!