Back button - ensuring order are not submitted twice (PHP)
Archive - Originally posted on "The Horse's Mouth" - 2007-04-28 07:55:18 - Graham EllisEnsuring that forms aren't "double submitted" is critically important on certain automated data entry applications - the classic example being an absolute need NOT to allow your user to place an order twice if he / she uses the "back" button and presses submit again.
I came across an article on a Java forum talking about redirect after Post, but I can't say that I'm thrilled. An over-complex solution and there's much easier ways of doing it in PHP (and in Java and other languages too!).
Almost inevitably, on line ordering systems are going to comprise a number of pages where you select your product(s) and then, as a final operation, confirm your order.
In PHP, you should use the $_SESSION superglobal to maintain the state of each individual user as he / she goes through your site, starting each operation that updates the embryonic order with a call to session_start. By default, values WILL be stored between pages in this super-global and the back button will leave the order-in-progress (a.k.a. the shopping cart) in tact - and that's ideal because you'll not want your customers to loose their selected products if they commit the 'crime' of doing a back.
But when one of your users selects the "yes, confirm my order" button or the equivalent, you DO want to prevent a step backwards resurrecting the data. There are two ways of doing this. The easiest is to do a session_destroy which eliminates the content of the shopping cart from the session when it's confirmed - the rest of your submit code for that page will have emailed the order confirmation, added the necessary information to your table of to-be-filled orders, and so on. The alternative way (if you don't want to loose the whole session - perhaps you want to leave your user logged in, for example) is to selectively clear the vital variables such as the cart-to-date form $_SESSION when the order is placed.
We have an example of this approach on our web site - try it out here and see the source code of the main application here. You'll note that this is part of a demonstration of the "four layer model" for major applications (you can write appliactions in PHP that have the beauty of A Picasso, or ones that look like the dog's dinner) - but that's a story for another entry.