转:http://blog.csdn.net/liutingxu1/article/details/18178783
最近在看php核心技术与开发实践,里面的这段放垃圾机器人刷表单的程序分享一下,自己写了一个简单的表单提交
[php] view plaincopy
- <?php
- /**
- * 模拟机器人来发表微博评论
- */
-
define('SECRET', '67%$#ap28');
- function m_token() {
- $str = mt_rand(1000, 9999);
- $str2 = dechex($_SERVER['REQUEST_TIME'] - $str);
- return $str . substr(md5($str . SECRET), 0, 10) . $str2;
-
}
- ?>
- <html>
- <meta charset="utf-8">
- <head>
- <title>提交验证</title>
- </head>
- <body>
- <form action="testcsrf.php" method="post" name="myform">
- <input name="user" value="" />
- <input type="submit" name="submit" value="提交" />
- <input type="hidden" name="token" value="<?php echo m_token();?>" />
- </form>
- </body>
- </html>
- testcsrf.php
- <?php
-
define('SECRET', '67%$#ap28');
- function v_token($str, $delay = 10) {
- $rs = substr($str, 0, 4);
- $middle = substr($str, 0, 14);
- $rs2 = substr($str, 14, 8);
- return ($middle == $rs.substr(md5($rs.SECRET), 0, 10)) &&
- ($_SERVER['REQUEST_TIME'] - hexdec($rs2) - $rs < $delay);
- }
- if(v_token($_POST["token"])){
-
echo "right";
- }else{
- echo "error";
- }
- ?>
- 上面这段代码也可以用作防止csrf攻击。
-