经过一个小例子,但愿对你们的PHP程序设计有帮助php
PHP代码html
1 <?php 2 #demo for prevent csrf 3 function encrypt($token_time) { 4 return md5('!@##$@$$#%43' . $token_time); 5 } 6 $token_time = time(); 7 $token = encrypt($token_time); 8 $expire_time = 10; 9 if ($_POST) { 10 $_token_time = $_POST['token_time']; 11 $_token = $_POST['token']; 12 if ((time() – $_token_time) > $expire_time) { 13 echo “expired token”; 14 echo "<br />"; 15 } 16 echo $_token; 17 echo "<br />"; 18 $_token_real = encrypt($_token_time); 19 echo $_token_real; 20 //compare $_token and $_token_real 21 } 22 ?>
HTML代码session
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta http-equiv=”content-type” content=”text/html; charset=utf-8″ /> 5 <title>test for csrf</title> 6 <meta http-equiv=”" content=”" /> 7 </head> 8 <body> 9 <form method=”post” action=”"> 10 <input type=”text” name=”text” id=”" value=”hello” /> 11 <input type=”hidden” name=”token” id=”" value=”<?php echo $token ?>” /> 12 <input type=”hidden” name=”token_time” id=”" value=”<?php echo $token_time ?>” /> 13 <input type=”submit” name=”submit” id=”" value=”submit” /> 14 </form> 15 </body> 16 </html>
经过验证码,在必定程度上消除了CSRF的风险,固然将token存入Session也是很好的ide
分析:post
token防攻击也叫做令牌,咱们在用户访问页面时就生成了一个随机的token保存session与表单了,用户提交时若是咱们获取到的token与session不同就能够提交从新输入提交数据了ui