Parsing PHP's way to prevent form recurrence

Source: Internet
Author: User
Tags commit current time echo date min php session php code reset setcookie
This article is a PHP to prevent form recurrence of the method of the detailed analysis of the introduction, the need for friends under the reference

PHP prevents forms from repeating instances:

Copy Code code as follows:


<?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 form repeat submission </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 cannot 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. nn";


error=1;


}





if (Error = = 1) {


alert (error_message);


return false;


} else {


frm_submit=true; Change Submit Status


return true;


}


}


-->


</script>


</head>


<body>


JavaScript and server-side dual-Prevent form repeat submission demo


<br/>


<br/>


now time: <?php echo Date ("y-m-d h:i:s");?>


<br/>


<br/>


<?php


if (@$_post["faction"]== "Submit" | | @$_get["Faction"]== "submit") {


//Submit processing





//***** server-side anti-repeat submission *******************


//If the form generation time from post is generated with the form saved by the session


//the same;
for normal submission

//Not the same;
for duplicate submission

if ($_session["fsess"]==$_post["fpsess"]) {


$_session["fsess"]=time ();


echo "Submit content: <br/>n";


echo $_post["fpsess"]. " <br/>n ";;


echo $_post["FormText"];


echo "</body></html>";


exit;


} else {


echo "Repeat commit, 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 form generation time-->


<input name= "faction" type= "hidden" value= "Submit"/>


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


<input type= "Submit" value= "submitted"/>


<input type= "reset" value= "reset"/>


</form>


</body>


</html>


*************************************************************
The above is a complete example, the following is a website excerpt, for reference only
*************************************************************
This is a tricky issue when users submit a form because of the speed of the network or if the Web page is maliciously refreshed, causing the same record to be repeatedly inserted into the database. We can start with the client and server side to try to avoid duplicate submissions of the same form.

1. Using client Script
referring to client-side scripting, JavaScript is often used for general input validation. In the following example, we use it to handle the recurrence of a form, see 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 being submitted, please wait ... '; Document.register.cont.disabled=true;document.the_form.submit (); " >
</form>
When the user clicks the Submit button, the button changes to a gray unavailable state.
The above example uses the OnClick event to detect the submission status of the user, and if the "submit" button is clicked, the button is immediately disabled and the user cannot click the button to submit again.
There is also a way to make use of JavaScript, but using the onsubmit () method, if the form has been submitted once, will immediately pop-up dialog box, the code is as follows:

Copy Code code as follows:


&lt;script language= "JavaScript" &gt;


&lt;!--


var submitcount=0;


function submitonce (form) {


if (Submitcount = = 0) {


submitcount++;


return true;


} else{


Alert ("is operating, please do not repeat the submission, thank you!") ");


return false;


}


}


//--&gt;


&lt;/script&gt;


&lt;form name= "The_form" method= "POST" action= "" onsubmit= "return Submitonce (This)" &gt;


&lt;input name= "text" type= "text" id= "text"/&gt;


&lt;input name= "cont" value= "submitted" type= "Submit" &gt;


&lt;/form&gt;


In the example above, if the user has clicked the Submit button, the script automatically records the current state and submitcount the variable by 1, and when the user tries to commit again, the script determines that the Submitcount variable value is Non-zero, prompting the user to commit, thus avoiding the repeated submission of the form.

2. Working with Cookies
use a cookie to record the status of the form submission, depending on its status to check whether the form has been submitted, see the following code:

Copy Code code as follows:


&lt;?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 submitted a form";


}


?&gt;


If the client prohibits cookies, this method will have no effect whatsoever, please note. For a detailed description of cookies, see Chapter 10th "PHP Session management."

3. Using session Processing
using PHP's session function, you can also avoid submitting forms repeatedly. Session is saved on the server side, PHP in the process of running can change the session variable, the next access to this variable, the new value is given, so, you can use a session variable record the value of the form submitted, if it does not match, the user is considered to repeat the submission, see the following code:

Copy Code code as follows:


&lt;?php


session_start ();


//Generate random number based on current session


$code = Mt_rand (0,1000000);


$_session[' code ' = $code;


?&gt;


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

Copy Code code as follows:


&lt;?php


session_start ();


if (isset ($_post[' originator ')) {


if ($_post[' originator '] = = $_session[' code ') {


//Processing the statement of the form, omitting the


}else{


Echo ' Please do not refresh this page or repeat the form! ';


}


}


?&gt;


As for the session, we'll discuss it in the 10th chapter, "PHP Conversation Management," and you can read the chapter directly and then go back to this section to continue reading.

4. Using the header function to turn
In addition to the above method, there is a simpler way, that is, when the user submits the form, server-side processing immediately to the other pages, the code is as follows.
if (Isset ($_post[' action ')) && $_post[' action '] = = ' submitted ') {
Working with data, such as inserting data, and immediately moving to another page
Header (' location:submits_success.php ');
}
This way, even if the user uses the Refresh key, it will not cause the form to be duplicated because it has moved to the new page, and the page script has ignored any submitted data.

Processing of 5.8.4 form expiration
in the development process, often appear the form error and return the page when the information is all lost, in order to support page bounce, you can use the following two ways to achieve.
1. Use header header to set cache control header Cache-control.
header (' Cache-control:private, Must-revalidate '); Support page Bounce

2. Use the Session_cache_limiter method.
Session_cache_limiter (' Private, must-revalidate '); To write before the Session_Start method
The following code fragment prevents users from filling out a form, and when you click the Submit button to return, the content you just filled out on the form will not be cleared:
Session_cache_limiter (' NoCache ');
Session_cache_limiter (' private ');
Session_cache_limiter (' public ');
Session_Start (); The
//below is the content of the form, so that when the user returns the form, the content that has been filled out is not emptied
and the code is posted to the top of the script to be applied. The
Cache-control message header field Description
Cache-control Specifies the caching mechanism that the request and response follow. Setting Cache-control in a request message or in a response message does not modify the caching process during another message handling process. The
cached instructions when requested 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.
Caching Directives
Description
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 handled by the shared cache. This allows the server to simply describe a partial response message to the user, 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 inadvertently released. Sending in a request message will cause neither the request nor the response message to use the cache
max-age
to indicate that the client can receive a lifetime that is not greater than the specified time, in secondsUnits)
Min-fresh
indicates that the client can receive response times less than the current time plus a specified time response
Max-stale
Indicates that the client can receive response messages that exceed the timeout period. If you specify a value for the Max-stale message, the client can receive a response message that exceeds the specified value for the timeout period

5.8.5 tips for judging form actions
forms can assign actions that should be handled by using the same program. There are different logic in the form, how to distinguish the user pressed button content is just a small problem.
In fact, just by submitting the button's name can be known, when the form is submitted, only the pressed button of the submit type will be sent to the form singular, so as long as the value of the button is available to know which button the user presses, 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, press the "B" button, then btn=b.
Alternatively, you can judge by the name of the Submit button (name), see 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 parameters have a or B, you can know which button is pressed.
<?php
Print_r ($_post);

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.