跨站攻擊就是利用程序上的一些細節(jié)或bug問題進行的了,那么我們要如何防止跨站攻擊呢?下面我們費話不說多了來給大家整理一個防止跨站攻擊例子,希望對各位有幫助.
php 防跨站攻擊測試例子代碼如下:
- <?php
- #demo for prevent csrf
- /**
- * enc
- */
- function encrypt($token_time) {
- return md5(‘!@##$@$$#%43′ . $token_time);
- }
- $token_time = time();
- $token = encrypt($token_time);
- $expire_time = 10;
- if ($_POST) {
- $_token_time = $_POST['token_time'];
- $_token = $_POST['token'];
- if ((time() – $_token_time) > $expire_time) {
- echo “expired token”;
- echo “<br />”;
- }
- echo $_token;
- echo “<br />”;
- $_token_real = encrypt($_token_time);
- echo $_token_real;
- //compare $_token and $_token_real
- }
- ?>
- <!DOCTYPE html>
- <html>
- <head>
- <meta http-equiv=”content-type” content=”text/html; charset=utf-8″ />
- <title>test for csrf</title>
- <meta http-equiv=”" content=”" />
- </head>
- <body>
- <form method=”post” action=”">
- <input type=”text” name=”text” id=”" value=”hello” />
- <input type=”hidden” name=”token” id=”" value=”<?php echo $token ?>” />
- <input type=”hidden” name=”token_time” id=”" value=”<?php echo $token_time ?>” />
- //開源代碼Vevb.com
- <input type=”submit” name=”submit” id=”" value=”submit” />
- </form>
- </body>
- </html>
通過在你的表單中包括驗證碼,事實上已經(jīng)消除了跨站請求偽造攻擊的風險,可以在任何需要執(zhí)行操作的任何表單中使用這個流程,當然,將token 存儲到session更好,這兒只是簡單示例下.
簡單分析:token防攻擊也叫作(令牌)了,我們在用戶訪問頁面時就生成了一個隨機的token保存session與表單了,用戶提交時如果我們獲取到的token與session不一樣就可以提交重新輸入提交數(shù)據(jù)了.
新聞熱點
疑難解答