預防CSRF

經過一個小例子,但願對你們的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 ?>
View Code

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>
View Code

經過驗證碼,在必定程度上消除了CSRF的風險,固然將token存入Session也是很好的ide

分析:post

token防攻擊也叫做令牌,咱們在用戶訪問頁面時就生成了一個隨機的token保存session與表單了,用戶提交時若是咱們獲取到的token與session不同就能夠提交從新輸入提交數據了ui

相關文章
相關標籤/搜索