一,操作
//设置$cookie = new CHttpCookie('mycookie','this is my cookie');$cookie->expire = time()+60*60*24*30; //有限期30天Yii::app()->request->cookies['mycookie']=$cookie;//获取$cookie = Yii::app()->request->getCookies();$test_cookie = $cookie['mycookie']->value;//删除unset($cookie['mycookie']);
二,注册
CApplication::registerCoreComponents()
protected function registerCoreComponents(){ $components=array( 'request'=>array( 'class'=>'CHttpRequest', ), ); $this->setComponents($components);}
三,源码
CHttpRequest::getCookies();
class CCookieCollection extends CMap{ protected function getCookies(){ $cookies=array(); if($this->_request->enableCookieValidation){ $sm=Yii::app()->getSecurityManager(); //获得安全管理器组件对象 //遍历cookie数据 foreach($_COOKIE as $name=>$value){ //是字符串 && 经过安全校验后等于原值则通过 if(is_string($value) && ($value=$sm->validateData($value))!==false) $cookies[$name]=new CHttpCookie($name,@unserialize($value)); } }else{ foreach($_COOKIE as $name=>$value) $cookies[$name]=new CHttpCookie($name,$value); } return $cookies; } //...}
CMap
class CMap extends CComponent implements IteratorAggregate,ArrayAccess,Countable{ public function offsetGet($offset){ return $this->itemAt($offset); } public function offsetSet($offset,$item){ $this->add($offset,$item); } public function offsetUnset($offset){ $this->remove($offset); } //....}