php prevents repeated submission of forms
Solution 1: Introduce cookie mechanism to solve
Submit the page code as follows a.php code is as follows: (Recommended learning: PHP programming from entry to proficiency)
<form id="form1" name="form1" method="post" action="t2.php"> <p>说明 <input type="text" name="titile" /> </p> <p> <input type="submit" name="Submit" value="提交" /> </p> </form> <?php setcookie("onlypost", 't'); //设置cookie,可以带上时间值。像有些论坛防止灌水就可以将你的一些基本信息存放到里面。 ?>
Php code
<?php if($_COOKIE['onlypost'] == 't'){ print_r($_COOKIE); //处理提交的内容 如果验证成功则处理 print "ok"; setcookie("onlypost", 'f'); //改变cooike值删除也可以了 } ?>
Disadvantages of the above processing: If the customer If cookies are disabled on the client, this method will have no effect. Please note this.
Solution 2: Use session (this is the same as JSP processing method)
Using PHP's Session function can also avoid repeated submission of forms. Session is saved on the server side. The Session variable can be changed while PHP is running. The next time you access this variable, you will get the newly assigned value. Therefore, you can use a Session variable to record the value submitted by the form. If it does not match, it is considered It is the user who is submitting repeatedly.
Code of page A:
<?php session_start(); //根据当前SESSION生成随机数 $code = mt_rand(0,1000000); $_SESSION['code'] = $code; //将此随机数暂存入到session ?> <form id="form1" name="form1" method="post" action="t2.php"> <p>说明 <input type="text" name="titile" /> <input type="hidden" name="originator" value="<?php echo $code;?>"> </p> <p> <input type="submit" name="Submit" value="提交" /> </p> </form> B页面: <?php session_start(); if(isset($_POST['originator'])) { if($_POST['originator'] == $_SESSION['code']){ echo "ok"; unset($_SESSION["code"]); //将其清除掉此时再按F5则无效 }else{ echo "请不要刷新本页面或重复提交表单"; } }?>
Solution 3: Redirect processing on the server side
if (isset($_POST['action']) && $_POST['action'] == 'submitted') { // 处理数据,如插入数据后,立即转向到其他页面 header('location:submits_success.php'); //效果与JSP里面的sendRedirect类似 }
The above is the detailed content of How to prevent repeated submission of forms in php. For more information, please follow other related articles on the PHP Chinese website!