How to parse php to prevent repeated form submission

Source: Internet
Author: User
Tags echo date php session

Php prevents repeated forms from submitting instances:

Copy codeThe Code is 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 repeated submission of forms </title>
<SCRIPT language = Javascript type = text/javascript>
<! --
// ****** Anti-repeated submission of Javascript ************
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 blank. \ 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 ";
Error = 1;
}

If (error = 1 ){
Alert (error_message );
Return false;
} Else {
Frm_submit = true; // change the submission status
Return true;
}
}
-->
</Script>
</Head>
<Body>
Javascript and server-side dual protection against repeated form submission demonstration
<Br/>
<Br/>
Current Time: <? Php echo date ("Y-m-d H: I: s");?>
<Br/>
<Br/>
<? Php
If (@ $ _ POST ["faction"] = "submit" | @ $ _ GET ["faction"] = "submit "){
// Submit for processing

*******************
// If the form generation time sent from POST and the form generation time saved by SESSION
// Same; normal submission
// Different; repeated submission
If ($ _ SESSION ["fsess"] ==$ _ POST ["fpsess"]) {
$ _ SESSION ["fsess"] = time ();
Echo "submitted content: <br/> \ n ";
Echo $ _ POST ["fpsess"]. "<br/> \ n ";;
Echo $ _ POST ["formtext"];
Echo "</body> Exit;
} Else {
Echo "submit again, quit !!!! <Br/> \ n ";
Echo "</body> 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>

**************************************** *********************
The above is a complete example. The following is an excerpt from the website for your reference only.
**************************************** *********************
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 malicious refreshing of the webpage. This is a tricky problem. We can start with the client and the server to avoid repeated submission of the same form.

1. Use client scripts
When it comes to client scripts, JavaScript is often used for regular input verification. In the following example, we use it to process the repeated submission of forms. Please refer to 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 = 'submitting. Please wait... '; document. register. cont. disabled = true; document. the_form.submit (); ">
</Form>
After you click the submit button, the button becomes unavailable.
In the above example, The OnClick event is used to detect the user's submission status. If you click the submit button, the button is immediately set to invalid. You cannot click the button to submit again.
Another method is to use JavaScript, but the OnSubmit () method is used. If a form has been submitted once, a dialog box is displayed immediately,The Code is as follows:

Copy codeThe Code is as follows: <script language = "javascript">
<! --
Var submitcount = 0;
Function submitOnce (form ){
If (submitcount = 0 ){
Submitcount ++;
Return true;
} Else {
Alert ("operation in progress. Please do not submit it again. 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 preceding example, if the user has clicked the submit button, the script automatically records the current status and adds the submitcount variable to 1. When the user tries to submit again, the script determines that the value of the submitcount variable is non-zero and prompts the user that the submitcount variable has been submitted to avoid repeated forms.

2. Use cookies for processing
Use cookies to record the status of the Form submission. You can check whether the form has been submitted based on its status. See the following code:

Copy codeThe Code is as follows: <? 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 ";
}
?>

If the client disables the Cookie, this method does not have any effect. Please note that. For more information about cookies, see Chapter 10th "PHP session management ".

3. Use Session Processing
Using the PHP Session function, you can avoid repeated forms. The Session is stored on the server. During PHP running, you can change the Session variable. The next time you access this variable, you get a new value. Therefore, you can use a Session variable to record the value submitted in the form. If the value does not match, it is considered that the user is submitting it repeatedly. See the following code:

Copy codeThe Code is as follows: <? Php
Session_start ();
// Generate a random number based on the current SESSION
$ Code = mt_rand (usd00 );
$ _ SESSION ['code'] = $ code;
?>

The random number is passed as a 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:
Copy codeThe Code is as follows: <? Php
Session_start ();
If (isset ($ _ POST ['originator']) {
If ($ _ POST ['originator'] = $ _ SESSION ['code']) {
// The statement for processing the form, omitted
} Else {
Echo 'Please do not refresh this page or submit the form again! ';
}
}
?>

For details about the Session content, we will discuss in Chapter 10th "PHP Session management". You can refer to this chapter directly and then return to this section to continue reading.

4. Use the header function to redirect
In addition to the above method, there is also a simpler method, that is, when the user submits the form, the server immediately redirects to other pages after processing, the Code is as follows.
If (isset ($ _ POST ['action']) & $ _ POST ['action'] = 'submitted '){
// Process the data. For example, after inserting the data, immediately go to another page.
Header ('location: submits_success.php ');
}
In this way, even if you use the refresh key, the form will not be submitted repeatedly because the page has been switched to a new page, and the page script has ignored any submitted data.

5.8.4 handling of form expiration
During the development process, forms often encounter errors and all information filled in when the page is returned is lost. To support page bounce, you can use either of the following methods.
1. Use the header to set the Cache control header Cache-control.
Header ('cache-control: private, must-revalidate'); // supports page Jump back

2. Use the session_cache_limiter method.
Session_cache_limiter ('Private, must-revalidate'); // before session_start
The following code snippet prevents users from entering the form from being cleared when they click the submit button to return the result:
Session_cache_limiter ('nocache ');
Session_cache_limiter ('private ');
Session_cache_limiter ('public ');
Session_start ();
// The following is the form content, so that the content already filled in will not be cleared when the user returns the form
Paste this code to the top of the script to be applied.
Cache-Control Message Header domain description
Cache-Control specifies the Cache mechanism that requests and responses follow. Setting Cache-Control in a request message or response message does not modify the Cache processing process of another message.
The cache commands for the request include no-cache, no-store, max-age, max-stale, min-fresh, and only-if-cached, commands in the Response Message include public, private, no-cache, no-store, no-transform, must-revalidate, proxy-revalidate, and max-age.
Cache command
Description
Public
Indicates that the response can be cached in any cache area.
Private
Indicates that the whole or part of the response message of 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 invalid for requests of other users.
No-cache
Indicates that the request or response message cannot be cached.
No-store
Used to prevent unintentional release of important information. Sending a request message does not cache the request and response messages.
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 a response whose response time is earlier than the current time plus the specified time.
Max-stale
Indicates that the client can receive response messages beyond the timeout period. If the value of the max-stale message is specified, the client can receive the response message beyond the timeout period.

5.8.5 skills for determining form actions
The form can be allocated with the action to be processed through the same program. There are different logics in the form. How to identify 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 a form is submitted, only the button of the submit type is pushed to the form array, so you only need to determine the button value 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. When the "B" button is pressed, btn = B.
You can also use the name of the submit button. 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>
In this way, as long as the POST/GET parameter contains 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.