Yii使用Cookies


Cookie允許資料跨請求持久化。在PHP中,可以通過 $_COOKIE 變數存取它們。Yii 中表示 cookie 作為 yii\web\Cookie 類的一個物件。在本章中,我們描述了讀取 cookie 的方法。
第1步- 在 SiteController 建立一個動作 actionReadCookies()方法。
public function actionReadCookies() { 
   // get cookies from the "request" component 
   $cookies = Yii::$app->request->cookies; 
   // get the "language" cookie value 
   // if the cookie does not exist, return "Py" as the default value 
   $language = $cookies->getValue('language', 'Py'); 
   // an alternative way of getting the "language" cookie value 
   if (($cookie = $cookies->get('language')) !== null) { 
      $language = $cookie->value; 
   } 
   // you may also use $cookies like an array 
   if (isset($cookies['language'])) { 
      $language = $cookies['language']->value; 
   } 
   // check if there is a "language" cookie 
   if ($cookies->has('language')) echo "Current language: $language"; 
}
第2步 - 在 SiteController 建立一個名為動作 actionSendCookies ()方法用於傳送 cookie 到用戶端。
public function actionSendCookies() { 
   // get cookies from the "response" component 
   $cookies = Yii::$app->response->cookies; 
   // add a new cookie to the response to be sent 
   $cookies->add(new \yii\web\Cookie([ 
      'name' => 'language', 
      'value' => 'Chinese', 
   ])); 
   $cookies->add(new \yii\web\Cookie([
      'name' => 'username', 
      'value' => 'Hippo', 
   ])); 
   $cookies->add(new \yii\web\Cookie([ 
      'name' => 'country', 
      'value' => 'China', 
   ])); 
} 
 第3步 - 現在,開啟 http://localhost:8080/index.php?r=site/send-cookies, 你會發現 cookies 已經儲存在瀏覽器內。
Yii使用Cookies
在Yii中預設情況下,cookie驗證已啟用。它保護 cookies 在用戶端被別人修改。在 config/web.php 檔案使用雜湊字串簽名每個 cookie。
<?php 
   $params = require(__DIR__ . '/params.php'); 
   $config = [ 
      'id' => 'basic', 
      'basePath' => dirname(__DIR__), 
      'bootstrap' => ['log'], 
      'components' => [ 'request' => [ 
            // !!! insert a secret key in the following (if it is empty) - this is 
            //required by cookie validation 
            'cookieValidationKey' => 'ywfdsa7829347898fLXfsCfdKjfO-fss0', 
         ], 'cache' => [ 
            'class' => 'yii\caching\FileCache', 
         ], 
         'user' => [ 
            'identityClass' => 'app\models\User', 
            'enableAutoLogin' => true, 
         ], 
         'errorHandler' => [ 
            'errorAction' => 'site/error', 
         ], 
         'mailer' => [ 
            'class' => 'yii\swiftmailer\Mailer', 
            // send all mails to a file by default. You have to set 
            // 'useFileTransport' to false and configure a transport 
            // for the mailer to send real emails. 
            'useFileTransport' => true, 
         ], 
         'log' => [ 
            'traceLevel' => YII_DEBUG ? 3 : 0, 
            'targets' => [ 
               [ 
                  'class' => 'yii\log\FileTarget', 
                     'levels' => ['error', 'warning'], 
                ], 
            ], 
         ], 
         'urlManager' => [ 
            //'showScriptName' => false, 
            //'enablePrettyUrl' => true, 
            //'enableStrictParsing' => true, 
            //'suffix' => '/' 
         ], 
         'db' => require(__DIR__ . '/db.php'), 
      ], 
      'modules' => [ 
         'admin' => [ 
            'class' => 'app\modules\admin\Admin', 
         ], 
      ], 
      'params' => $params,
   ]; 
   if (YII_ENV_DEV) { 
      // configuration adjustments for 'dev' environment 
      $config['bootstrap'][] = 'debug'; 
      $config['modules']['debug'] = [ 
         'class' => 'yii\debug\Module', 
      ]; 
      $config['bootstrap'][] = 'gii'; 
      $config['modules']['gii'] = [ 
         'class' => 'yii\gii\Module', 
      ]; 
   } 
   return $config; 
?>
可以通過設定 yii\web\Request::$enableCookieValidation 屬性為 false。