预防CSRF

通过一个小例子,希望对大家的PHP程序设计有帮助

PHP代码

 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代码

 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也是很好的

分析:

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

转载于:https://www.cnblogs.com/sxmcACM/p/4069662.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值