Yii - 使用 Cookies
Cookies 允许数据在请求之间持久保存。在 PHP 中,您可以通过 $_COOKIE 变量访问它们。Yii 将 cookie 表示为 yii\web\Cookie 类的对象。在本章中,我们描述了几种读取 cookie 的方法。
步骤 1 − 在 SiteController 中创建一个 actionReadCookies 方法。
public function actionReadCookies() { // 从"request"组件获取 cookies $cookies = Yii::$app->request->cookies; // 获取"language"cookie 值 // 如果 cookie 不存在,则返回"ru"作为默认值 $language = $cookies->getValue('language', 'ru'); // 获取"language"cookie 值的另一种方法 if (($cookie = $cookies->get('language')) !== null) { $language = $cookie->value; } // 您也可以像数组一样使用 $cookies if (isset($cookies['language'])) { $language = $cookies['language']->value; } // 检查是否存在"language"cookie if ($cookies->has('language')) echo "Current language: $language"; }
步骤 2 − 要查看发送 cookie 的实际操作,请在 SiteController 中创建一个名为 actionSendCookies 的方法。
public function actionSendCookies() { // 从"response"组件获取 cookie $cookies = Yii::$app->response->cookies; // 向要发送的响应添加新的 cookie $cookies->add(new \yii\web\Cookie([ 'name' => 'language', 'value' => 'ru-RU', ])); $cookies->add(new \yii\web\Cookie([ 'name' => 'username', 'value' => 'John', ])); $cookies->add(new \yii\web\Cookie([ 'name' => 'country', 'value' => 'USA', ])); }
步骤 3 − 现在,如果您转到 http://localhost:8080/index.php?r=site/send-cookies,您会注意到 cookie 已保存在浏览器内。
在 Yii 中,默认情况下启用 cookie 验证。它可以保护 cookie 不被客户端修改。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 //cookie 验证所需 'cookieValidationKey' => 'ymoaYrebZHa8gURuolioHGlK8fLXCKjO', ], 'cache' => [ 'class' => 'yii\caching\FileCache', ], 'user' => [ 'identityClass' => 'app\models\User', 'enableAutoLogin' => true, ], 'errorHandler' => [ 'errorAction' => 'site/error', ], 'mailer' => [ 'class' => 'yii\swiftmailer\Mailer', // 默认将所有邮件发送到一个文件。您必须设置 // 'useFileTransport' 为 false 并配置传输 // 以便邮件程序发送真实的电子邮件。 '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' => [ 'hello' => [ 'class' => 'app\modules\hello\Hello', ], ], 'params' => $params, ]; if (YII_ENV_DEV) { // 针对"dev"环境的配置调整 $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 来禁用 cookie 验证。