Home >Backend Development >PHP Problem >How to prohibit repeated submission of forms in php
php method to prohibit repeated submission of forms: first add an input hidden field to the form; then its value is used to save the token value; then when the page is refreshed, the token value will change, and the token value will be determined after submission Is it correct? Finally, if the token submitted in the foreground does not match the background, it is considered a duplicate submission.
php method to prohibit repeated submission of forms:
First make restrictions from 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.
Related learning recommendations: php programming (video)
Second, we can redirect the page after submission, That is, jumping to a new page after submission is mainly to avoid repeated submissions with F5, but it also has 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{ ?> <form method="post" action=""> <input type="hidden" name="token" value="<?php echo $_SESSION['token']?>"> <input type="text" class="input" name="web" value="www.jb51.net"> <input type="submit" class="btn" value="提交" /> </form> <?php } ?>
Related learning recommendations: Programming video
The above is the detailed content of How to prohibit repeated submission of forms in php. For more information, please follow other related articles on the PHP Chinese website!