yii操作cookie的方法


这两个方法分别是设置cookie和获取cookie值的方法。对yii现有的方法进行封装,方便使用。

/**
     * @param $name
     * @param $data
     * @param int $duration
     */
    public function saveCookie($name,$data,$duration=86400){
        $app = Yii::app();
        $cookie = new CHttpCookie($name,$data);
        $cookie->expire = time() + $duration;
        $cookie->value = $app->getSecurityManager()->hashData(serialize($data));
        $app->getRequest()->getCookies()->add($cookie->name, $cookie);
    }

    /**
     * @param $name
     * @return mixed|null
     */
    public function getCookie($name){
        $app = Yii::app();
        $cookies=$app->getRequest()->getCookies();
        if($cookies['name'] && $cookies['name']->value){
            return unserialize($app->getSecurityManager()->validateData($cookies[$name]->value));
        }
        return null;
    }

Archives