Simple PRG Pattern PHP

php | prg

Note: The code below is also moved to a composer based class:

Use a form or link pointing to a webform, where you want to use the simple_prg function. If you use a form as a entry point, you will need to add a hidden field with the name start_prg, and set this with some value, e.g. 1.

If you use a link, then you just postfix your link href with start_rest and set this to a value.

For a longer explantion of the PRG pattern see the wiki article about it.

The simple_prg function can be used for e.g. a shopping cart, where you want your users to reload and move back and forth between posts, without the browser making warnings about 'reposting'. The function is based on sessions and therefor it will not retain the form entries for longer time than your sessions allows.

When clients arrive to your webpage where you want to use the simple RPG function, then you just call the following function: simple_prg(). Then everything should work out if your session is started!


function simple_prg ($start_prg = false, $request_uri = null){
    // check to see if we should start prg
    if ($_SERVER['REQUEST_METHOD'] == 'POST'){
        $uniqid = uniqid();
        $_SESSION['post'][$uniqid] = $_POST;
        if (!$request_uri){
            $request_uri = 'REQUEST_URI';
        header("HTTP/1.1 303 See Other");
        $header = "Location: " . $_SERVER[$request_uri] . '?prg=1&uniqid=' . $uniqid;
        //header('Expires: ' . gmdate('D, d M Y H:i:s', time()+1000) . ' GMT');        

    if ($start_prg){        
        // on start we clean all session posts
        @$_SESSION['post'] = '';
    } else {
        if (isset($_GET['prg'])){
            $uniqid = $_GET['uniqid'];
            $_POST = @$_SESSION['post'][$uniqid];

// we need to be in session

// include file where the function simple_prg exists
include "../lib/common.php";

// depending on the $_GET['start_prg'] we clear or history
// of posts or we do not.
if (isset($_GET['start_prg'])){
    // this will clear the stored post vars in session
    // e.g. /example.php?start_prg=1
    simple_prg(true, 'PHP_SELF');
} else {
    // when this is called we can browse back and forward and
    // reload without getting notice about 'reloading browser
    simple_prg(null, 'PHP_SELF');

// a post form
function form_test (){ ?>
<form method ="post" action = "">
<input type ="text" name="test" value="<?=@$_POST['test']?>" /> <br />
<input type ="submit" name="submit" value="Send!" /> 
<?php }

// call post form

This page has been viewed 1162 times. First hit: 05-Nov-2016 14:22:48
Share email, Google+, Twitter, Facebook.
comments powered by Disqus