How to prevent duplicate posts via a browser refresh? [closed]
Will the following stop accidental duplicate entries in my database if the user posts a form and then clicks the browser refresh button?
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' ) {
try {
// write to database
} catch($e) {
// error reporting
}
}
?>
Use Post-Redirect-Get pattern - redirect always after data were successfully submitted.
No, because if they click the refresh button (or back/forward, whatever) the browser will attempt to POST again. What you want is the Post/Redirect/Get paradigm. Note that this will only prevent duplicate submissions via navigation. If you want to prevent duplicate submissions from multiple clicks of a form submission, you have to use javascript to disable the button in some way during the post attempt.
Some code:
<?php
if ('POST' == $_SERVER['REQUEST_METHOD']) {
//do processing
//303 forces a GET request
header("Location: thank-you-page", true, 303);
exit;
}
else {
//handle bad page visit.
}
?>
I don't see any code there that does anything to differentiate between a first post and a duplicate post. What you should do is redirect the browser to a different URL after processing the POST so that if they press refresh, they're not refreshing the target of the form and POSTing again.
You should use Dan Grossman's method, always redirect after a POST action. Also this is another option, which adds extra security:
Add a one-time token to your forms and save it to the $_SESSION
-variable. Then if it is used (form is submitted), remove it from the session (or create a new token). If the form is then sent again, the two tokens don't match and you have a duplicate entry (you can ignore the second for example).
精彩评论