商会资讯

 找回密码
 立即注册

QQ登录

只需一步,快速开始

用新浪微博连接

一步搞定

搜索
热搜: 活动 交友 discuz
查看: 6444|回复: 0
打印 上一主题 下一主题

PHP防csrf攻击

[复制链接]

109

主题

1

好友

3774

积分

管理员

Rank: 9Rank: 9Rank: 9

  • ta_mind
    mb_qb7
    2013-3-19 01:56
  • classn_01: 366 classn_02

    [LV.9]以坛为家II

    跳转到指定楼层
    楼主
    发表于 2017-12-9 10:54:57 |只看该作者 |倒序浏览
    由于用户可能会从其他途径POST过来,因此我们需要防止这种情况

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

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

    index.php 页面:
    [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>  


    [php] view plain copy

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

    [php] view plain copy

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

    [php] view plain copy

    • temp.php页面:  

    [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 '测试失败';  
    •     }  



    分享到: QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
    分享分享0 收藏收藏0 转发到微博
    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    回顶部