YII Framework学习之request与response用法(基于CHttpReq(4)

为了防止csrf,yii提供了相应的方法

CSRF(Cross-site request forgery),中文名称:跨站请求伪造,也被称为:one click attack/session riding,缩写为:CSRF/XSRF。
CSRF的攻击方式详解 黑客必备知识

public function getCsrfToken() { if($this->_csrfToken===null) { $cookie=$this->getCookies()->itemAt($this->csrfTokenName); if(!$cookie || ($this->_csrfToken=$cookie->value)==null) { $cookie=$this->createCsrfCookie(); $this->_csrfToken=$cookie->value; $this->getCookies()->add($cookie->name,$cookie); } } return $this->_csrfToken; } protected function createCsrfCookie() { $cookie=new CHttpCookie($this->csrfTokenName,sha1(uniqid(mt_rand(),true))); if(is_array($this->csrfCookie)) { foreach($this->csrfCookie as $name=>$value) $cookie->$name=$value; } return $cookie; } public function validateCsrfToken($event) { if($this->getIsPostRequest()) { // only validate POST requests $cookies=$this->getCookies(); if($cookies->contains($this->csrfTokenName) && isset($_POST[$this->csrfTokenName])) { $tokenFromCookie=$cookies->itemAt($this->csrfTokenName)->value; $tokenFromPost=$_POST[$this->csrfTokenName]; $valid=$tokenFromCookie===$tokenFromPost; } else $valid=false; if(!$valid) throw new CHttpException(400,Yii::t('yii','The CSRF token could not be verified.')); } }

对于$_GET的使用,不仅仅可以使用$_GET和以上提供的相关方法,在action中,可以绑定到action的方法参数。

这里就一并罗列官方给出的说明。

从版本 1.1.4 开始,Yii 提供了对自动动作参数绑定的支持。 就是说,控制器动作可以定义命名的参数,参数的值将由 Yii 自动从 $_GET 填充。

为了详细说明此功能,假设我们需要为 PostController 写一个 create 动作。此动作需要两个参数:

category: 一个整数,代表帖子(post)要发表在的那个分类的ID。
language: 一个字符串,代表帖子所使用的语言代码。
从 $_GET 中提取参数时,我们可以不再下面这种无聊的代码了:

class PostController extends CController { public function actionCreate() { if(isset($_GET['category'])) $category=(int)$_GET['category']; else throw new CHttpException(404,'invalid request'); if(isset($_GET['language'])) $language=$_GET['language']; else $language='en'; // ... fun code starts here ... } }

现在使用动作参数功能,我们可以更轻松的完成任务:

class PostController extends CController { public function actionCreate($category, $language='en') { $category=(int)$category; // ... fun code starts here ... } }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/46c5ea7a78fbab6b34e851824cd6355f.html