当前位置:首页 > PHP教程 > php应用 > 列表

php 防跨站攻击测试例子

发布:smiling 来源: PHP粉丝网  添加日期:2014-08-21 10:19:44 浏览: 评论:0 

跨站攻击就是利用程序上的一些细节或bug问题进行的了,那么我们要如何防止跨站攻击呢?下面我们费话不说多了来给大家整理一个防止跨站攻击例子,希望对各位有帮助.

php 防跨站攻击测试例子代码如下:

  1. <?php 
  2. #demo for prevent csrf 
  3.  
  4. /** 
  5. * enc 
  6. */ 
  7. function encrypt($token_time) { 
  8. return md5(‘!@##$@$$#%43′ . $token_time); 
  9. } 
  10.  
  11. $token_time = time(); 
  12. $token = encrypt($token_time); 
  13. $expire_time = 10; 
  14.  
  15. if ($_POST) { 
  16. $_token_time = $_POST['token_time']; 
  17. $_token = $_POST['token']; 
  18.  
  19. if ((time() – $_token_time) > $expire_time) { 
  20. echo “expired token”; 
  21. echo “<br />”; 
  22. } 
  23.  
  24. echo $_token; 
  25. echo “<br />”; 
  26. $_token_real = encrypt($_token_time); 
  27.  
  28. echo $_token_real; 
  29. //compare $_token and $_token_real 
  30. } 
  31. ?> 
  32.  
  33. <!DOCTYPE html> 
  34. <html> 
  35. <head> 
  36. <meta http-equiv=”content-type” content=”text/html; charset=utf-8″ /> 
  37. <title>test for csrf</title> 
  38. <meta http-equiv=”" content=”" /> 
  39. </head> 
  40. <body> 
  41. <form method=”post” action=”"> 
  42. <input type=”text” name=”text” id=”" value=”hello” /> 
  43. <input type=”hidden” name=”token” id=”" value=”<?php echo $token ?>” /> 
  44. <input type=”hidden” name=”token_time” id=”" value=”<?php echo $token_time ?>” /> 
  45. //开源代码phpfensi.com 
  46. <input type=”submit” name=”submit” id=”" value=”submit” /> 
  47. </form> 
  48. </body> 
  49. </html> 

通过在你的表单中包括验证码,事实上已经消除了跨站请求伪造攻击的风险,可以在任何需要执行操作的任何表单中使用这个流程,当然,将token 存储到session更好,这儿只是简单示例下.

简单分析:token防攻击也叫作(令牌)了,我们在用户访问页面时就生成了一个随机的token保存session与表单了,用户提交时如果我们获取到的token与session不一样就可以提交重新输入提交数据了.

Tags: php防跨站攻击 php跨站攻击

分享到:

相关文章