cookie的設置:
在components文件夾創建CKhelper.php文件
namespace app\components; use yii\web\Cookie; class CKhelper { /* *\yii::$app->request|\yii::$app->response下的cookie都是CookieCollection的對象 * \yii::$app->request 下的CookieCollection的readonly屬性爲true 只能讀不能寫 * \yii::$app->response 下的CookieCollection的readonly屬性爲false 不是隻讀的 */ public static function set($key,$val,$expire=1200){ $cook=new Cookie(); $cook->name =$key; $cook->value =$val; $cook->expire =time()+$expire; \yii::$app->response->cookies->add($cook); } public static function get($key){ return \yii::$app->response->cookies->get($key); } public static function getValue($key){ return \yii::$app->request->cookies->getValue($key,false); } /* * 不是刪除瀏覽器客戶端所有的cookie而是,刪除本次請求對cookie的所有寫操作 * 即不改變當前瀏覽器的cookie狀態 */ public static function del(){ //\yii::$app->response->cookies->remove($key); \yii::$app->response->cookies->removeAll(); } }在控制器中調用即可
<?php /** * Created by PhpStorm. * User: Administrator * Date: 2016/7/13 * Time: 17:06 */ namespace app\controllers; use app\components\CKhelper; use yii\base\Controller; class CookController extends Controller { public function actionIndex(){ CKhelper::set('username','哈哈'); CKhelper::set('nickname','aa'); } public function actionGet(){ //echo CKhelper::get('nickname'); $res=CKhelper::getValue('username'); echo"<pre>"; print_r($_COOKIE); } public function actionDel(){ CKhelper::del(); } }