How to use CSRF in Yii automatic.与csrf token 无法被验证

What is CSRF, please see the details here. http://en.wikipedia.org/wiki/Cross-site_request_forgery

In Yii, how to start the CSRF authorization? It is very easy to do that.

Just add this to main.php

'components'=>array(
    'request'=>array(
    'enableCsrfValidation'=>true,
    ),
),
And then, do something else to send a request to the server, you have to provide the  YII_CSRF_TOKEN ( the browser will do for us when click a link), otherwise, you will get this message

The CSRF token could not be verified.
when you post a form, if you do not use CActiveForm or its children, you have to provide a hidden field to store the YII_CSRF_TOKEN.

<input type="hidden" name="YII_CSRF_TOKEN" value="<?php echo Yii::app()->request->csrfToken; ?>" />
If you use CActiveForm or its children, you just use the same code no matter you set enableCsrfValidation to true or false.

<?php $form=$this->beginWidget('CActiveForm'); ?>
Yii will know how to do it!

Have fun with Yii! :)

以上内容转载自:http://www.cnblogs.com/davidhhuan/archive/2011/01/19/1939253.html

今天在项目中开启了enableCsrfValidation

结果发现选择一级分类后,无法提取二级分类的内容。通过抓包,得到:csrf token 无法被验证。解决办法:要在提交数据中附上YII_CSRF_TOKEN

<tr>
<td width="10%"><?php echo $form->labelEx($model, 'sid')?></td>
<td width="90%"><div class="mm_div_left"><?php echo CHtml::activeDropDownList($model,
    'fid',
    Costcategory::getCategory(),
    array(
        'empty'=>'请选择',
        'ajax'=>array(
            'type'=>'POST',
            'url'=>CController::createUrl('cost/dynamiccities'),
            'update'=>'#Cost_sid',
            'data'=>array('fid'=>'js:this.value','YII_CSRF_TOKEN'=>Yii::app()->request->csrfToken),
        )
    ));

   echo CHtml::activeDropDownList($model, 'sid',
            Costcategory::getCategory($model->fid),
                array(
                    'empty'=>'请选择',
                )
            ); ?>
    </div>
    <div class="mm_div_right"><?php echo $form->error($model, 'sid');?></div>
</td>
</tr>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值