How to prevent multiple inserts when submitting a form in PHP?



PHP session can be used to prevent multiple inserts when submitting a form. PHP session sets a session variable (say $_SESSION['posttimer']) that sets the current timestamp on POST. Before processing the form in PHP, the $_SESSION['posttimer'] variable is checked for its existence and checked for a specific timestamp difference (say 2 or 3 seconds). This way, those insertions that are actually duplicates can be identified and removed.

Simple form −

// form.html
<form action="my_session_file.php" method="post">
   <input type="text" name="bar" />
   <input type="submit" value="Save">
</form>

The reference to ‘my_session_file.php’ in the above will have the below lines of code −

Example

if (isset($_POST) && !empty($_POST)) {
   if (isset($_SESSION['posttimer'])) {
      if ( (time() - $_SESSION['posttimer']) <= 2) {
         // less then 2 seconds since last post
      } else {
         // more than 2 seconds since last post
      }
   }
   $_SESSION['posttimer'] = time();
}

Output

This will produce the following output −

The unique form submitted data.

The posttimer session variable is set and when there is a time difference of 2 seconds or less before the last POST operation, it can be removed. Otherwise it is stored. The time function is called and the value is assigned to the posttimer session variable.


Advertisements