PHP防csrf攻击

 

PHP防csrf攻击

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

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


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


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


index.php 页面:

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

 
   
[php]  view plain  copy
  1. "background-color: rgb(255, 255, 255);">  
  2.   
[php]  view plain  copy
  1. "background-color: rgb(255, 255, 255);">  
  2.   
[php]  view plain  copy
  1. temp.php页面:  
[php]  view plain  copy
  1. "code" class="php">
  2. session_start();  
  3.     if(isset($_POST['user']) && $_SESSION['csrf'] == $_POST['csrf']){  
  4.         echo '测试通过且 csrf:'.$_SESSION['csrf'];  
  5.     }else{  
  6.         echo '测试失败';  
  7.     }  

你可能感兴趣的:(PHP防csrf攻击)