Paul
Paul

Reputation: 1614

Reload/refresh page in browser without re-submitting form?

I have a form on a php page that is submitted to the same page. I noticed that if I reload/refresh the page the form gets re-submitted. How do I code to avoid this in the most easy way?

Upvotes: 5

Views: 29085

Answers (3)

Igor Parra
Igor Parra

Reputation: 10348

This assume a lot of things, but maybe is what you are looking for:

if ($_POST)
{
    $success = false;

    /*
     * if all goes OK managing POST data make $success = true;
     * 
     */

    if ($success)
    {
        // this will redirects to your original
        // form's page but using GET method
        // so re-submitting will be no possible
        header("location: {$_SERVER['PHP_SELF']}");
        exit;
    }
}

Upvotes: 3

martinstoeckli
martinstoeckli

Reputation: 24071

One possibility is, to implement the post-redirect-get approach.

Simply said, a POST request will be never delivered to the browser. Instead you execute all necessary actions and store the information you need in the session, and then you make a redirect with code 303.

$page = 'show_result.php';
header('Location: '.$page, true, 303);
exit;

Doing it this way, the browser will show the "show_result.php" page (a GET request) instead of the page requested with POST. This is also the page that is added to the history, so refreshing and using the back button will never do another POST request. As a nice side effect you get rid of browser warnings about resending data, normally the user cannot decide what to do then anyway.

I think the biggest problem with this approach is, that you need a session to store error messages, that means you have to rely on cookies. If you do no redirect to display errors, the browser will show the warning about resending data.

Upvotes: 3

Your Common Sense
Your Common Sense

Reputation: 157839

According to HTTP standard, you ought to make browser to do a GET request after sending POST one.
Here is a sketch example to do the form handling:

<?  
if ($_SERVER['REQUEST_METHOD']=='POST') {  

  $err = array();
  //performing all validations and raising corresponding errors
  if (empty($_POST['name']) $err[] = "Username field is required";  
  if (empty($_POST['text']) $err[] = "Comments field is required";  

  if (!$err) {  
    //if no errors - saving data and redirect
    header("Location: ".$_SERVER['PHP_SELF']);
    exit;
  }  else {
    // all field values should be escaped according to HTML standard
    foreach ($_POST as $key => $val) {
      $form[$key] = htmlspecialchars($val);
    }
} else {
  $form['name'] = $form['comments'] = '';  
}
include 'form.tpl.php';
?>  

Upvotes: 0

Related Questions