<?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{ ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <title>演示:PHP防止重复提交表单</title> <meta name="keywords" content="PHP" /> <meta name="description" content="" /> <link rel="stylesheet" type="text/css" href="http://www.helloweba.com/demo/css/main.css" /> <style> .demo{width:300px; margin:60px auto 10px auto} @media only screen and (min-width: 420px) { .demo{width:500px; margin:60px auto 10px auto} } .btn { text-transform: uppercase; background: rgb(0, 100, 0); color: white; padding: 10px 20px; border-radius: 5px;border:none; cursor: pointer;margin:10px auto;width:100px;text-align:center; } .btn:hover {background: rgb(0, 75, 0);text-decoration:none} .input{width:200px;height:22px; padding:4px;border:1px solid #d3d3d3} </style> </head> <body> <div id="main"> <h2 class="top_title"><a href="http://www.helloweba.com/view-blog-332.html">PHP防止重复提交表单</a></h2> <div class="demo"> <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> </div> </div> <script> </script> </body> </html> <?php }?>