How to prevent form resubmission when the page is refreshed in PHP?

Last Updated on Feb 19, 2024

form resubmission dialog

Form resubmission when refreshed happens when you don't get out of the page after submitting the form.

There are two ways of preventing the form resubmission.

  • Using AJAX to handle form submission.
  • Redirect the page after the form submission.

In this tutorial, we will focus on redirecting the page after form submission.

  1. Make sure you have POST request

    First, make sure that you are using a POST request in your form. To do that, set the method attribute to post in your form element.

    <form method="post">
    
  2. Redirect the page after your operation

    Then, after doing your operation, redirect the page to another page or the same page. And if you need to retain the information or output a success or error message, you can pass it via session.

    if(isset($_POST['insert'])) {
      // Your operation here
    	
      $_SESSION['MESSAGE'] = "Successfully Added!";
      header("Location: samepage.php");
      die();
    }
    
  3. Destroy the session

    Finally, destroy the session after using it so that when the user refreshes the page, it will no longer display the message.

    echo empty($_SESSION['MESSAGE']) ? '' : $_SESSION['MESSAGE']; 
    unset($_SESSION['MESSAGE']);
    

Conclusion

We can prevent the form resubmission by redirecting the page to another or the same page after our operation. Then, using session, we can pass a success or error message to that page or even retain the POST data. Finally, after using the session, we can destroy it so that when the user refreshes the page, it will no longer display it.

© John Michael Balbarona