Basic Post Redirect Get (PRG) design pattern in PHP

Post/Redirect/Get (PRG) is a web development design pattern that is used by the developers to prevent unwanted form resubmissions on their software. In software engineering, the term design pattern is an existing reusable solution to an occurring problem within a given condition in software design. It is a description for how to implement the very best solution of a certain problem in the software development.  

POST is one of the most common HTTP methods.

Some other notes on POST requests:

  • POST requests are never cached
  • POST requests do not remain in the browser history
  • POST requests cannot be bookmarked
  • POST requests have no restrictions on data length
Post/Redirect/Get Design pattern solution on succesful login

Since POST requests cannot be bookmarked by the browser, we need to implement the the post / redirect / get design pattern to prevent form submission duplicates. E.g. when a users submits a form and reloads the web pages, if not implementing PRG, the form will get resubmitted resulting in unwanted behaviour.

Below is a basic script in PHP of PRG.

//store current url into a variable  
$self = htmlspecialchars($_SERVER["PHP_SELF"]);  
//if form is submitted via POST method  
if ($_POST) {  
    //303 redirect to the same page  
    header('Location: ' . $self, true, 303);  
    //exit from the current script  
Please follow and like us:

Leave a Reply

Your email address will not be published. Required fields are marked *