Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP avoid browser reposting $_POST on page refresh?

Tags:

html

post

refresh

I wonder what are the techniques i can use to avoid users to post form twice when they refresh page and chose submit again?

e.g. i have form inside regiter.php and process it as well inside register.php.

1st i could process in another file e.g. register_process.php and redirect to register.php, but then i have to create about 20 new pages and relocate a lot of code, i dont want that option.

2nd i could play with headers i dont remember exact trick but had some bad experience with that - users seen old data on page after refreshing it...

3rd i could just redirect upon success to some dummy.php and from dummy.php jump back to register.php then even if they refresh page browser would not re-post, however it does not protect against them using back button and choosing re-post, i know i could expire page, but i find that annoying experience for me and probably other users to see page expired error.

4th use some unique "access key" for each form once page loaded that will post with form and once used cannot be reused, however i kind of struggle with logics of that feature. how do know key was used without storing it in MySQL DB, i think time based accesis not great either because some users can take long between page open and form submit.

I need more suggestions how to avoid users reposing form again.

like image 414
Petja Zaichikov Avatar asked Dec 15 '12 04:12

Petja Zaichikov


2 Answers

Try this:

<?php
session_start();
if( strcasecmp($_SERVER['REQUEST_METHOD'],"POST") === 0) {
  $_SESSION['postdata'] = $_POST;
  header("Location: ".$_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING']);
  exit;
}
if( isset($_SESSION['postdata'])) {
  $_POST = $_SESSION['postdata'];
  unset($_SESSION['postdata']);
}

This will basically save the POST data and cause the browser to re-request as a GET request.

like image 154
Niet the Dark Absol Avatar answered Oct 24 '22 19:10

Niet the Dark Absol


5th. Use AJAX or jQuery and when the form is clicked on the page submit that data in the background. Output a response to the screen. Mark that form as submitted, or save to a session, and when they refresh they will not be able to submit the form again.

In my opinion it is the best way to do it anyway. I had a scoreboard with 20 or more forms it is worked really well to send the data without refreshing. You can return a response and make the page look very professional. Using jQuery you can also use some great form validation to make sure that they are submitting the fields that are required.

like image 32
donlaur Avatar answered Oct 24 '22 20:10

donlaur