Eight Simple and Effective Strategies to Prevent Repeated Form Submissions

Form duplication is one of the most common and troublesome problems in multi-user web applications. There are many application scenarios that encounter repeated submission problems, such as:

  • Click the submit button twice.
  • Click the refresh button.
  • Repeating the previous action with the browser back button resulted in repeated submission of the form.
  • Repeat form submission using browser history.
  • Browser repeated HTTP requests.

When a user submits a form, the same record may be repeatedly inserted into the database due to the speed of the network or the webpage is maliciously refreshed, which is a difficult problem. We can start with the client side and the server side together and try to avoid repeated submissions of the same form. The following is a collection of 8 common and effective ways to prevent repeated form submissions: Source www.bkjia.com

 

1. js disables the submit button.

Use Javascript to disable the submit button after the form is submitted. This approach prevents impatient users from clicking the button multiple times. But there is a problem, if the client side disables Javascript, this method will not work.


My previous article said that using some Jquery plugins works well. Reference: js method and code to prevent repeated form submission

 

2. Use Post/Redirect/Get mode.

Perform page redirection after submission, this is the so-called Post-Redirect-Get (PRG) pattern. In short, when the user submits the form, you perform a client-side redirection to the submission success message page.

This avoids the double submission caused by the user pressing F5, and it also does not have the browser form double submission warning, and also eliminates the same problem caused by pressing forward and backward in the browser.

 

3. Store a special flag in the session.

On the server side, generate a unique identifier, store it in the session, and write it into the hidden field of the form, and then send the form page to the browser. After the user enters the information, click submit, and on the server side, get the form The value of the hidden field in the session is compared with the unique identifier in the session. If it is equal, it means that it is submitted for the first time, so the request will be processed, and then the unique identifier in the session will be removed; if it is not equal, it means that it is submitted repeatedly and will not be processed.

 

This gives your web application more advanced XSRF protection.

See the following code:

<?php  
session_start();  
//根据当前SESSION生成随机数  
$code = mt_rand(0,1000000);  
$_SESSION['code'] = $code;  
?>  
在页面表单上将随机数作为隐藏值进行传递,代码如下:  
<input type="hidden" name="originator" value="<?=$code?>">  
   
    在接收页面的PHP代码如下:  
   
<?php  
session_start();  
if(isset($_POST['originator'])) {  
if($_POST['originator'] == $_SESSION['code']){  
// 处理该表单的语句,省略  
}else{  
echo ‘请不要刷新本页面或重复提交表单!’;  
}  
}  
?>  

 

4. Use the header function to turn

In addition to the above method, there is a simpler method, that is, when the user submits the form, the server-side processing immediately turns to other pages, the code is as follows.

if (isset($_POST['action']) && $_POST['action'] == 'submitted') {

/ / Process data, such as inserting data, immediately turn to other pages

header('location:submits_success.php');

}

In this way, even if the user uses the refresh key, it will not cause repeated submission of the form, because it has turned to a new page, and the page script has ignored any submitted data.

 

5. Processing of form expiration

In the development process, it often happens that the form is wrong and all the information filled in when returning to the page is lost. In order to support the page bounce, the following two methods can be used.

1. Use the header header to set the Cache-control header.

header('Cache-control: private, must-revalidate'); //Support page jump back

2. Use the session_cache_limiter method.

session_cache_limiter('private, must-revalidate'); //Write before session_start method

The following code snippet prevents the user from filling out the form, and clicking the "Submit" button to return, the content just filled in on the form will not be cleared:

session_cache_limiter('nocache');

session_cache_limiter('private');

session_cache_limiter('public');

session_start();

//The following is the content of the form, so that when the user returns to the form, the content that has been filled in will not be cleared

Paste this code at the top of the script you want to apply.

Cache-Control message header field description

Cache-Control specifies the caching mechanism that requests and responses follow. Setting Cache-Control in a request message or a response message does not modify the caching process in another message process.

The cache instructions at the time of request include no-cache, no-store, max-age, max-stale, min-fresh and only-if-cached, and the instructions in the response message include public, private, no-cache, no-store, no-transform, must-revalidate, proxy-revalidate, and max-age. The meaning of the instructions in each message is shown in Table 5-3.

Table 5-3

cache instruction

illustrate

public

Indicates that the response can be cached by any buffer

private

Indicates that the entire or partial response message for a single user cannot be processed by the shared cache. This allows the server to describe only part of the user's response message, which is not valid for other users' requests

no-cache

Indicates that the request or response message cannot be cached

no-store

Used to prevent important information from being released unintentionally. Sending in the request message will make the request and response messages not use the cache

max-age

Indicates that the client can receive responses with a lifetime not greater than the specified time (in seconds)

min-fresh

Indicates that the client can receive responses with a response time less than the current time plus the specified time

max-stale

Indicates that the client can receive response messages beyond the timeout period. If you specify a value for max-stale messages, the client can receive response messages that exceed the value specified in the timeout period

For an introduction to sessions and cookies, see Chapter 10, "PHP Session Management" for details.

6. Skills for judging form actions

Forms can use the same program to assign actions that should be processed. There are different logics in forms. How to determine the content of the button pressed by the user is just a small problem.

In fact, you only need to know the name of the submit button. When the form is submitted, only the button of type submit will be sent to the form array, so you can know where the user presses by judging the value of the button. A button, take the following form as an example:

<FORM method="POST" Action=test.php>

<input type=submit name="btn" value="a">

<input type=submit name="btn" value="b">

</FORM>

When the user presses the "a" button, btn=a, and when the "b" button is pressed, then btn=b.

In addition, it can also be judged by the name of the submit button, see the following code:

<FORM method="POST" Action=test.php>

<input type=submit name="a" value="提交A">

<input type=submit name="b" value="提交B">

</FORM>

In this way, as long as there is a or b in the parameter of POST/GET, you can know which button is pressed.

<?php

print_r($_POST);

?>

 

7. Add constraints in the database.

Add unique constraints or create unique indexes in the database to prevent duplicate data. This is the most effective way to prevent double submission of data.

How did you overcome the data duplication problem? Have you come across any real-world examples of duplicating data submissions?

Reprinted from: http://www.bkjia.com/jingyan/471187.html

5. Use client-side scripting

When it comes to client-side scripting, JavaScript is often used for general input validation. In the following example, we use it to deal with the repeated submission of the form, please see the code below:

<form method="post" name="register" action="test.php" enctype="multipart/form-data">

<input name="text" type="text" id="text" />

<input name="cont" value="提交" type="button" onClick="document.register.cont.value='正在提交,请等待...';document.register.cont.disabled=true;document.the_form.submit();">

</form>

When the user clicks the "Submit" button, the button will be grayed out and unavailable.

In the above example, the OnClick event is used to detect the user's submission status. If the "Submit" button is clicked, the button is immediately set to an invalid state, and the user cannot click the button to submit again.

 

8. Handling with Cookies

Use cookies to record the status of form submission, according to its status, you can check whether the form has been submitted, see the following code:

<?php

if(isset($_POST['go'])){

setcookie("tempcookie","",time()+30);

header("Location:".$_SERVER[PHP_SELF]);

exit();

}

if(isset($_COOKIE["tempcookie"])){

setcookie("tempcookie","",0);

echo "您已经提交过表单";

}

?>

Note that this method will have no effect if cookies are disabled by the client. For a detailed introduction to cookies, see Chapter 10, "PHP Session Management".

PS: These methods for preventing repeated submission of the form can be used for reference. I have used the first method to prevent the form from being submitted multiple times.

The source is collected and sorted by the Home of the Guest. Please indicate the source for reprinting: www.bkjia.com/jingyan/

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326940833&siteId=291194637