PHP防csrf攻击

 

PHP防csrf攻击

标签: CSRFPHP
  2829人阅读  评论(0)  收藏  举报
  分类:

由于用户可能会从其他途径POST过来,因此我们需要防止这种情况


原理:在页面生成一个随即串并保存在token中,用于在服务器中比对


index.php 与 temp.php  两个页面示范


index.php 页面:

[php]  view plain  copy
  1. <pre name="code" class="php"><?php  
  2.     session_start();  
  3.     $csrf = md5(uniqid(rand(), TRUE));  //生成token  
  4.     $_SESSION['csrf'] = $csrf;  
  5. ?>  
  6. <meta charset="utf-8">  
  7. <form action="temp.php" method="post" name="form1" idf="form1">  
  8.     测试:<input type="text" name="user" id="user">  
  9.     <input type="hidden" name="csrf" id="csrf" value="<?php echo $csrf;?>">  
  10.     <input type="submit" name="submit" value="提交">  
  11. </form>  

 
 
[php]  view plain  copy
  1. <span style="background-color: rgb(255, 255, 255);">  
  2. </span>  
[php]  view plain  copy
  1. <span style="background-color: rgb(255, 255, 255);">  
  2. </span>  
[php]  view plain  copy
  1. temp.php页面:  
[php]  view plain  copy
  1. <pre name="code" class="php"><?php  
  2. session_start();  
  3.     if(isset($_POST['user']) && $_SESSION['csrf'] == $_POST['csrf']){  
  4.         echo '测试通过且 csrf:'.$_SESSION['csrf'];  
  5.     }else{  
  6.         echo '测试失败';  
  7.     }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值