admin 发表于 2017-12-9 10:54:57

PHP防csrf攻击

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

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

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

index.php 页面:
view plain copy


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


view plain copy


[*]<span style="background-color: rgb(255, 255, 255);">  
[*]</span>  

view plain copy


[*]<span style="background-color: rgb(255, 255, 255);">  
[*]</span>  

view plain copy


[*]temp.php页面:  

view plain copy


[*]<pre name="code" class="php"><?php  
[*]session_start();  
[*]    if(isset($_POST['user']) && $_SESSION['csrf'] == $_POST['csrf']){  
[*]        echo '测试通过且 csrf:'.$_SESSION['csrf'];  
[*]    }else{  
[*]        echo '测试失败';  
[*]    }  



页: [1]
查看完整版本: PHP防csrf攻击