PHP+Session Solution to Prevent Form Repeated Submission
- 2021-09-20 19:43:54
- OfStack
index.php
The current form page is_submit is set to 0
SESSION_START();
$_SESSION['is_submit'] = 0;
<form id="reg" action="post.php" method="post">
<p> User name: <input type="text" class="input" name="username" id="user"></p>
<p> Dense Code: <input type="password" class="input" name="password" id="pass"></p>
<p>E-mail : <input type="text" class="input" name="email" id="email"></p>
<p><input type="submit" name="submit" class="btn" value=" Submit registration "/></p>
</form>
post.php
If the form is submitted, set the current 'is_submit to 1. If post. php is refreshed, the else code will be executed
SESSION_START();
if (isset($_POST['submit'])) {
if ($_SESSION['is_submit'] == '0') {
$_SESSION['is_submit'] = '1';
echo " Code block, things to do, code ...<a onclick='history.go(-1);' href='javascript:void(0)'> Return </a>";
} else {
echo " Please do not submit it repeatedly <a href='index.php'>PHP+SESSION Prevent forms from being submitted repeatedly </a>";
}
}
Introduction of php Implementation Method for Solving Repeated Submission of Forms
[Introduction] Repeated submission is a problem that we often encounter in our development. Besides using js to prevent repeated submission of forms, we can also use php to prevent repeated submission.
The code for Example 1 is as follows
Repeated submission is a problem that we often encounter in our development. Besides using js to prevent repeated submission of forms, we can also use php to prevent repeated submission.
Example 1
The code is as follows
<?php
/*
* php How to prevent repeated submission of forms in
*/
session_start();
if (empty($_SESSION['ip'])) {// No. 1 1 A write operation is performed to determine whether a record has been recorded IP Address to know if you want to write to the database
$_SESSION['ip'] = $_SERVER['REMOTE_ADDR']; // No. 1 1 Second write, paving the way for the judgment of refreshing or retreating later
//...........// Write to database operation
} else {// There is already a number 1 The operation after the second write is no longer written to the database
echo ' Please do not refresh and go back again '; // Write 1 Some written tips or other things
}
?>
Specific principle
session range variable token to prevent.
1. Turn on session:
session_start();
2. If a form is submitted
Copy the code as follows
if (isset($token))
token is included in form in the form of hidden.
Copy the code as follows
<input type="hidden" name="token" value="<?php echo $token; ?>" />
3. If the form is submitted repeatedly
The code is as follows
if ($_SESSION["token"] != $token) {
// Do not allow duplicate submissions, process them here
// header("location:".$_SERVER['PHP_SELF']);
} else {
// Normal form submission, processed here
// echo " Submitted ";
}
4. Set the token value
The code is as follows
$token = mt_rand(0,1000000);
$_SESSION['token'] = $token;
Summarize