Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Stop a Form from being accidentally reprocessed when Back is pressed

What is the best way to stop a form from being reprocessed when a user hits a Back button?

I'm following the Post/Redirect/Get pattern, so I don't have a problem if F5 is pushed, but the back button still provides the opportunity to resubmit the form. If this form is a credit card processing page, this is bad.

This question has been asked somewhat here, but the phrasing and answers were of poor quality and not specific to this problem exactly.

I have form.php which submits to itself. If there were no errors in input data upon submission, the user is redirected to form_thanks.php. Hitting back (and "Send" or "Resubmit") once resubmits form.php (BAD!) and then brings them back to form_thanks.php.

Please also include solutions that do not involve using Sessions, if possible.

like image 987
philfreo Avatar asked Dec 29 '22 12:12

philfreo


2 Answers

I would do it a different way. Put up a hidden input with a random string as the value, and when it's submitted store that random string in a session. Set up a simple check to see if they've already posted it and if they have don't accept the input.

like image 143
Whitey Avatar answered Jan 01 '23 02:01

Whitey


This should be done with a single-use token, or a nonce. The php/server should include this token in a hidden form field.

It should store a list of all the recent tokens and each time a form is submitted, it should check to see if the token is in the list of recent valid tokens.

If it's not in the list, then don't reprocess the form.
If it is in the list, then process the form and remove the token from the list.

The tokens can be handled within sessions or just a simple database table without sessions. The tokens should be user-specific though.

This is also the recommended way to avoid CSRF attacks.

like image 31
philfreo Avatar answered Jan 01 '23 00:01

philfreo