Introduction to how to solve the problem of repeated form submission in PHP
Repeated submission is a problem we often encounter in development. In addition to using js to prevent repeated submission of forms, we can also use php to prevent repeated submission.
Example 1
The code is as follows. Copy the code
/*
* How to prevent repeated submission of forms in php
*/
session_start();
if (empty($_SESSION['ip'])) {//The first write operation, determine whether the IP address is recorded, so as to know whether to write to the database
$_SESSION['ip'] = $_SERVER['REMOTE_ADDR']; //First write, paving the way for subsequent refresh or retreat decisions
//..........//Write to database operation
} else {//There has been an operation after the first write, so it will no longer be written to the database
echo 'Please do not refresh and go back again'; //Write some already written prompts or other things
}
?>
Specific principles
Session scope variable token to prevent.
1. Open session:
session_start();
2. If there is a form submission
The code is as follows. Copy the code
if (isset($token))
The token is included in the form in hidden form.
The code is as follows. Copy the code
3. If the form is submitted repeatedly
The code is as follows. Copy the code
1.if ($_SESSION["token"] != $token) {
2. // Do not allow repeated submissions, handle them here
3. // header("location:".$_SERVER['PHP_SELF']);
4.} else {
5. // Normal form submission, processed here
6. // echo "Submitted";
7.}
4. Set token value
The code is as follows. Copy the code
1.$token = mt_rand(0,1000000);
2.$_SESSION['token'] = $token;
Introduction to how to solve the problem of repeated form submission in PHP
------Solution--------------------
Should users be allowed to submit for the second time under normal circumstances?
------Solution--------------------
Actually I didn’t do that
Because mature projects generally separate views and forward them through routing! This will not happen!