Recommended: "PHP Video Tutorial"
When we submit the form, we cannot ignore it The restriction is to prevent users from submitting the form repeatedly, because it is possible that the user clicks the submit button continuously or the attacker maliciously submits data. Then we will get into trouble when processing after submitting the data, such as modifying or adding data to the database.
So how to avoid the phenomenon of repeated form submission? We can start from many aspects:
First limit the front-end. The front-end JavaScript is disabled after the button is clicked once. This method simply prevents multiple clicks on the submit button, but the disadvantage is that it will not work if the user disables the JavaScript script.
Second, we can redirect the page after submission, that is, jump to a new page after submission. This mainly avoids repeated F5 submissions, but there are also shortcomings.
Third, the database makes unique index constraints.
Fourth, is to do session token verification.
Let’s now take a look at a simple method of using session token to prevent repeated submission of forms.
We add an input hidden field in the form, that is, type="hidden", whose value is used to save the token value. When the page is refreshed, the token value will change. After submission, it is judged whether the token value is correct. , if the token submitted in the frontend does not match the token submitted in the backend, it is considered to be a duplicate submission.
< ?php / PHP简单利用token防止表单重复提交 */ 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; } //如果token为空则生成一个token if(!isset($_SESSION['token']) || $_SESSION['token']=='') { set_token(); } if(isset($_POST['web'])){ if(!valid_token()){ echo "token error,请不要重复提交!"; }else{ echo '成功提交,Value:'.$_POST['web']; } }else{ ?> } ?>
The above is a simple example to prevent repeated submission of forms.
In actual project development, the form token will be processed more complexly, which is what we call token verification. Possible processing includes: verifying the source domain, that is, the origin, whether it is an external submission; matching the action to be performed, whether it is adding, modifying or deleting; the second and most important thing is to construct a token, which can use a reversible encryption algorithm. Might be complicated because plaintext is still insecure.