POST/REQUEST/GET Pattern in PHP

The “do you want to resend the POST data to the website again?” error message a user gets when they try to refresh or go back to a page really scares them. Understandably, since the browser often says “this could mean you’ll pay for the item twice!”.

The first way to fix that is by sending all form data over an AJAX request. But if the user has javascript disabled then you’ll need to fall back to my next suggestion anyway.

The POST/REQUEST/GET (PRG) pattern removes that possibility by never allowing the user to fall onto a page which POST data has been sent to. Putting it simply, whenever you want POST data, you take it and then immediately redirect them.

You do the redirect by using a HTTP1.1 303, and although that sounds a little hacky it’s what was intended for that status to be used for.

You can see a gist with sample code here.

In that example I used a SESSION in order to give feedback. Although as a stackoverflow post points out, you could also send data back using GET variables (as the pattern truly intended). Sessions are handy for when you don’t want the user always coming back to the page, or when you don’t want to put sensitive data in the URL.

PRG is particularly important these days with single page Javascript applications becoming more popular. I came across this with my notebook application, where trying to refresh would annoyingly bring up “would you like to resubmit [your log in data]?”, which adds friction to the flow.

Further reading:

Comments are closed.