reproduced. https://blog.csdn.net/yanhui_wei/article/details/50772380
When we submit the form, a limitation that cannot be ignored is to prevent the user from submitting the form repeatedly, because it is possible that the user continuously clicks the submit button or the attacker maliciously submits the data, then our processing after submitting the data, such as modifying or adding data to the database will get into trouble.
So how to avoid the phenomenon of repeated form submission? We can start in many ways, starting with the front-end constraints. Front-end JavaScript is disabled after the button is clicked once, that is, disabled. This method simply prevents multiple clicks of the submit button, but the disadvantage is that it will fail if the user disables the JavaScript script. Second, we can do redirect page redirection after submission, that is, jump to a new page after submission, mainly to avoid repeated submission of F5, but there are also shortcomings. The third is that the database does a unique index constraint. Fourth, is to do session token verification.
Let's now look at a simple way to use session tokens to prevent repeated form submissions.
We add an input hidden field to the form, that is, type="hidden", and its value is used to save the token value. When the page is refreshed, the token value will change. After submitting, it is judged whether the token value is correct. If it does not match the background, it is considered to be a duplicate submission.
- <?php
- /*
- * PHP simply uses token to prevent repeated form submission
- */
- session_start();
- header("Content-Type: text/html;charset=utf-8");
- function set_token() {
- $_SESSION['token'] = md5(microtime(true));
- }
- function valid_token() {
- $return = $_REQUEST['token'] === $_SESSION['token'] ? true : false;
- set_token();
- return$return;
- }
- //If the token is empty, generate a token
- if(!isset($_SESSION['token']) || $_SESSION['token']=='') {
- set_token();
- }
- if(isset($_POST['web'])){
- if(!valid_token()){
- echo "token error, please do not submit again!" ;
- }else{
- echo 'Successfully submitted, Value:' . $_POST [ 'web' ];
- }
- }else{
- ?>
- <form method="post" action="">
- <input type="hidden" name="token" value="<?php echo $_SESSION['token']?>">
- <input type="text"class="input" name="web" value="www.helloweba.com">
- <input type="submit"class="btn" value="提交" />
- </form>
- <?php
- }
- ?>