Mawg Mawg - 1 year ago 222
PHP Question

Simple Post-Redirect-Get code example

I have found many sites that describes PRG, but no simple PHP code example.

Here's what I implemented:

  1. The
    has an action:

  2. The
    is never seen by the user; if validates all
    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.

  3. Whichever HTML is generated get stored in a
    variable and then
    header('Location: <as appropriate>);

  4. The
    (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?

Answer Source

Simplest scenario:

if ($_POST) {
   // Execute code (such as database updates) here.

   // Redirect to this page.
   header("Location: " . $_SERVER['REQUEST_URI']);

Use REQUEST_URI. Do not use PHP_SELF as in most CMS systems and frameworks PHP_SELF would refer to /index.php.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download