(转)PHP防止表单重复提交

防止重复提交表单的方法网上蛮多的,有js的也有用cookie和session的,我用的方法是session来判断的。
下面贴上几种方法:
一:js:<input type="button" value="只提交一次" onclick="this.disabled=true;this.form.submit()" /> 把按钮变成灰色
jquery代码:

JavaScript代码
  1. <script type="text/javascript">        
  2. $("input:submit").each(function() {        
  3. var srcclick = $(this).attr("onclick");        
  4. if(typeof(srcclick)=="function"){        
  5. $(this).click(function() {        
  6. if (srcclick()) {        
  7. setdisabled(this);        
  8. return true;        
  9. }        
  10. return false;        
  11. });}        
  12. });        
  13. function setdisabled(obj) {        
  14. setTimeout(function() { obj.disabled = true; }, 100);        
  15. }        
  16. </script>     

 



二:php中cookie方法:

t1.php

XML/HTML代码
  1. <form id="form1" name="form1" method="post" action="t2.php">      
  2.     <p>说明       
  3.         <input type="text" name="titile" />      
  4. </p>      
  5.     <p>      
  6.         <input type="submit" name="Submit" value="提交" />      
  7. </p>      
  8. </form>     


PHP代码

PHP代码
  1. <?php        
  2. setcookie("onlypost", 't'); //设置cookie       
  3. ?>     
  4.   
  5. t2.php   
  6. PHP代码   
  7. <?php       
  8.       
  9. if($_COOKIE['onlypost'] == 't'){       
  10.            
  11.      print_r($_COOKIE);       
  12.     //处理提交的内容       
  13.      setcookie("onlypost", 'f'); //改变 cooike值 删除也可以了       
  14. }       
  15.       
  16. // 其他代码       
  17.       
  18.       
  19. ?>     



三:session方法,也就是我用的:

t1.php

XML/HTML代码
  1. <form id="form1" name="form1" method="post" action="t2.php">      
  2.     <p>说明       
  3.         <input type="text" name="titile" />      
  4. </p>      
  5.     <p>      
  6.         <input type="submit" name="Submit" value="提交" />      
  7. </p>      
  8. </form>     

 

PHP代码
  1. <?php        
  2. $_SESSION['onlypost']="t"//设置session   
  3. ?>    

t2.php

PHP代码

 

  1. <?php       
  2.       
  3. if($_SESSION['onlypost']=="t"){       
  4.            
  5.      print_r($_SESSION);       
  6.     //处理提交的内容       
  7.     $_SESSION['onlypost']=="f"; //改变 session的值 删除也可以了       
  8. }       
  9.       
  10. // 其他代码       
  11.       
  12.       
  13. ?>     
posted @ 2014-02-24 14:26  念雷星  阅读(146)  评论(0编辑  收藏  举报