php Preventing Form Repeated Submission Example Explanation

  • 2021-11-24 00:57:58
  • OfStack

I'm ashamed to say that I made a low-level mistake when I was doing the project a few days ago. Do form submission in the background of the company, 1 is used by your own employees, 2 is written by html, and the form is not verified to be submitted repeatedly, and the result is wrong. Write it down and record it to remind yourself that you can't neglect it at all times.

Solution

In fact, there are many ways, just give a few simple examples.

Framework

Many frameworks have the function of preventing repeated submission, which should be understood by everyone, so I won't repeat it here.

Front end

The principle is very simple. After the user clicks Submit, use JS to gray out the Submit button.

Back end

That is to say, PHP is used for verification, but of course it is not limited to the following types

Cookie

The user submits the form to the back end and marks it in Cookie. Repeated submission within the specified time is invalid. However, when the user disables Cookie, this method will fail.


<?php
 
if (isset($_COOKIE['formFlag'])) {
  exit('error');
}
 
//  Processing data 
 
// 30 Invalid repeated submissions within seconds 
setcookie('formFlag', time(), time() + 30);

Session

When the form page is presented, random numbers are generated and stored both in Session and in the form hidden field. On the first commit, the comparison successfully deleted the value in Session.


<?php
 
if (!isset($_SESSION['formFlag']) || $_POST['formFlag'] != $_SESSION['formFlag']) {
  exit('error');
}
 
//  Processing data 
 
unset($_SESSION['formFlag']);

The above is the introduction of PHP to prevent repeated submission of the full content of the form, thank you for the support of this site.


Related articles: