Avoiding form resubmit in php when pressing f5

Your method could work in theory, but there's a much easier way.

After submitting the form successfully, perform a redirect. It doesn't matter where to, but it'll clear the $_POST.

header('Location: http://www.example.com/form.php');

In your case, it sounds like you want to redirect to the page you're already on. Append a $_GET parameter to the URL if you want to display a confirmation message.

Hope this helps,

Tom


The best way to handle forms is to use self-submission and a redirect. Something like this:

if (isset($_POST)) {
  // Perform your validation and whatever it is you wanted to do
  // Perform your redirect
}

// If we get here they didn't submit the form - display it to them.

Using the CodeIgniter framework:

function index() {
  $this->load->library('validation');
  // Your validation rules

  if ($this->form_validation->run()) {
    // Perform your database changes via your model
    redirect('');
    return;
  }
  // The form didn't validate (or the user hasn't submitted)
  $this->load->view('yourview');
}

The solution is a pattern commonly known as Post/Redirect/Get