I have found many sites that describes PRG, but no simple PHP code example.
Here's what I implemented:
form.php
has an action: validate.php
.validate.php
is never seen by the user; if validates all $_GET
and, if valid writes it to database and generates the HTML of a confirmation page / if not valid, it generates the HTML of an error page explaining what is wrong. $_SESSION
variable and then validate.php
calls header('Location: <as appropriate>);
.submitted.php
of invalid_input.php
(in case the user reads the URL) consists only of echo $_SESSION['form_html'];
.That seems to me like protection against both page reload and back button problems.
Did I goof by trying to reinvent the wheel?
POST: A form is sent to the server with a post-request and an entry in the database is changed. Redirect: After a post request, the correct webpage with the changed data is delivered to the client using the redirect instruction (HTTP 303). GET: The client requests a confirmation page.
With PRG the browser ends up making two requests. The first request is a POST request and is typically used to modify data. The server responds with a Location header in the response and no HTML in the body. This causes the browser to be redirected to a new URL.
Simplest scenario:
if ($_POST) { // Execute code (such as database updates) here. // Redirect to this page. header( "Location: {$_SERVER['REQUEST_URI']}", true, 303 ); exit(); }
Use REQUEST_URI
. Do not use PHP_SELF
as in most CMS systems and frameworks PHP_SELF
would refer to /index.php
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With