Parse php's method to prevent repeated form submissions

  • 2020-07-21 07:04:26
  • OfStack

php prevents duplicate form submission instances:


<?php
 session_start();
 $_SESSION['fsess']=($_SESSION['fsess'])?$_SESSION['fsess']:time();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title> Prevent duplicate form submissions </title>
<SCRIPT language=Javascript type=text/javascript>
<!--
//*****Javascript Anti-repeat submission ************
var frm_submit=false;   // Record submission status 
function check_form(fobj) {
 var error = 0;
    var error_message = "";
 if (fobj.formtext.value=="")
 {
  error_message = error_message + "formtext  Can't be empty .\n";
  error = 1;
 }

 if (frm_submit==true) {
  error_message = error_message + " This form has been submitted .\n Please wait patiently for the server to process your request .\n\n";
  error=1;
 }

 if (error == 1) {
   alert(error_message);
   return false;
 } else {
   frm_submit=true;  // Change commit status 
   return true;
 }
}
-->
</script>
</head>
<body>
Javascript And the server side   Double prevent the form from resubmitting the demo 
<br/>
<br/>
 Current Time: <?php echo date("Y-m-d H:i:s"); ?>
<br/>
<br/>
<?php
if(@$_POST["faction"]=="submit"||@$_GET["faction"]=="submit"){
 // Submit processing 

 //***** The server side prevents duplicate submissions *******************
 // if POST Incoming form generation time and SESSION Saved form generation time 
 // The same; Submit as normal 
 // Not the same; For duplicate submission 
 if($_SESSION["fsess"]==$_POST["fpsess"]){
  $_SESSION["fsess"]=time();
  echo  " Content submitted: <br/>\n";
  echo  $_POST["fpsess"]."<br/>\n";;
  echo  $_POST["formtext"];
  echo "</body></html>";
  exit;
 } else {
  echo  " Repeat submission, exit!! <br/>\n";
  echo "</body></html>";
  exit;
 }
} 
//$_SESSION["fsess"]=time();
?>
<form name="f_info" action="" method="post"  onSubmit="return check_form(this);">
<input name="fpsess" type="hidden" value="<?php echo $_SESSION["fsess"]; ?>" />
<!--  Save the form generation time  -->
<input name="faction" type="hidden" value="submit" />
<input name="formtext" id="formtext" type="text" value="" />
<input type="submit" value=" submit " />
<input  type="reset" value=" reset " />
</form>
</body>
</html>

*************************************************************
Above is a complete example, the following is excerpted in the website, for reference only
*************************************************************
When the user submits the form, the same record may be repeatedly inserted into the database due to the network speed or the webpage is maliciously refreshed, which is a tricky problem. We can start with client and server 1 and try to avoid duplicate submissions with form 1.

1. Use client-side scripts
When it comes to client-side scripts, JavaScript is often used for general input validation. In the following example, we use it to handle duplicate form submissions, as shown in the following code:
< form method="post" name="register" action="test.php" enctype="multipart/form-data" >
< input name="text" type="text" id="text" / >
< input name = "cont value" = "submit" type = "button onClick" = "document. register. cont. value = 'is submitted, please wait... '; document. register. cont. disabled = true; document. the_form. submit ();" >
< /form >
When the user clicks the Submit button, the button becomes gray and unavailable.
In the example above, the OnClick event is used to detect the user's submission status. If the "Submit" button is clicked, the button is immediately invalidated and the user cannot click the button to submit again.
There is another method, which also USES the function of JavaScript, but USES the method OnSubmit(). If the form has been submitted once, the dialog box will pop up immediately. The code is as follows:


<script language="javascript">
<!--
var submitcount=0;
function submitOnce (form){
if (submitcount == 0){
     submitcount++;
     return true;
} else{
    alert(" Operating, please do not repeat submission, thank you! ");
    return false;
}
}
//-->
</script>
<form name="the_form" method="post" action="" onSubmit="return submitOnce(this)">
<input name="text" type="text" id="text" />
<input name="cont" value=" submit " type="submit">
</form>

In the above example, if the user has clicked the "submit" button, the script automatically records the current state and adds submitcount variable to 1. When the user tries to submit again, the script determines that the value of submitcount variable is non-zero and prompts the user to have submitted, thus avoiding repeated submission of the form.

2. Use Cookie for processing
Use Cookie to record the status of form submission, and check whether the form has been submitted according to its status. 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 " You have already submitted the form ";
}
?>

Note that this method will not work if the client disables Cookie. For more information on Cookie, see Chapter 10, PHP Session Management.

3. Use Session for processing
Taking advantage of PHP's Session features, you can also avoid resubmitting forms. Session is saved on the server side, and the variable Session can be changed during the operation of PHP. The next time this variable is accessed, the new value will be obtained. Therefore, one Session variable can be used to record the value submitted by the form.


<?php
    session_start();
    // Based on the current SESSION Random number generation 
    $code = mt_rand(0,1000000);
    $_SESSION['code'] = $code;
?>

Pass the random number as hidden value on the page form. The code is as follows:
< input type="hidden" name="originator" value=" < ?=$code? > " >
The PHP code on the receiving page is as follows:

<?php
session_start();
if(isset($_POST['originator'])) {
    if($_POST['originator'] == $_SESSION['code']){
        //  The statement for processing the form is omitted 
    }else{
        echo  'Please do not refresh this page or resubmit the form! ';
    }
}
?>

We will discuss Session in more detail in chapter 10, "PHP session Management", which you can refer to directly before returning to this section to continue reading.

4. Turn using the header function
In addition to the above method, there is an even simpler method, that is, when the user submits the form, the server side processes it and immediately moves to another page, as shown in the code below.
if (isset($_POST['action']) & & $_POST['action'] == 'submitted') {
// After processing data, such as inserting data, immediately move to another page
header('location:submits_success.php');
}
This way, even if the user USES the refresh key, the form will not be resubmitted because it has moved to a new page and the page script will no longer pay attention to any submitted data.

5.8.4 Processing of form expiration
In the development process, it often happens that all the information filled in when the form is returned to the page is lost due to errors. In order to support page hops, the following two methods can be implemented.
1. Set the cache control header Cache-ES120en with header header.
header (' Cache - control: private, must - revalidate '); // Support page hops

2. Use the session_cache_limiter method.
session_cache_limiter (' private, must - revalidate '); // Before the session_start method
The following code snippet prevents the user from filling out the form and clicking the "Submit" button to return without clearing what was just filled out on the form:
session_cache_limiter('nocache');
session_cache_limiter('private');
session_cache_limiter('public');
session_start();
// The following is the form content so that when the user returns to the form, the content that has been filled in will not be emptied
Stick this code at the top of the script you want to apply.
Cache-Control message header field specification
Cache-Control specifies the caching mechanism that requests and responses follow. Setting Cache-ES160en in a request or response message does not modify the cache processing in another message processing.
The cache instructions on request include no-cache, ES164en-store, ES166en-ES167en, ES168en-ES169en, ES170en-ES171en and ES172en-ES173en-ES174en, The instructions in the response message include public, private, ES177en-ES178en, ES179en-ES180en, ES181en-ES182en, ES183en-ES184en, ES185en-ES186en and ES187en-ES188en.
Cache directives
Said Ming
public
Indicates that the response can be cached by any cache
private
Indicates that the response message for a single user, in whole or in part, cannot be processed by the Shared cache. This allows the server to only describe when part of a user's response message is not valid for other user requests
no-cache
Indicates that the request or response message cannot be cached
no-store
Used to prevent important information from being inadvertently released. Sending in the request message makes both the request and response messages non-cached
max-age
Indicates that the client can receive a response with a lifetime of no more than a specified number of seconds
min-fresh
Indicates that the client can receive a response with a response time less than the current time plus a specified time
max-stale
Indicates that the client can receive a response message that exceeds the timeout period. If the value of the ES212en-ES213en message is specified, the client can receive a response message that exceeds the specified value for the period

5.8.5 Skills for judging form actions
Forms can be assigned actions that should be processed by the same program, and with different logic in the form, it's just a matter of determining the content of a button pressed by the user.
In fact, it can be known only through name of the submit button. When the form is submitted, only the submit button will be sent to the form array. Therefore, the user can know which button is pressed by judging the value of the button.
< 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 presses the "b" button, then btn=b.
You can also judge by the name of the submit button (name), as shown in the following code:
< FORM method="POST" Action=test.php >
< input type=submit name="a" value=" Submit A" >
< input type=submit name="b" value=" submit B" >
< /FORM >
So as long as the POST/GET parameter has a or b, you can know which button is pressed.
< ?php
print_r($_POST);
? >


Related articles: