Yii 使用Cookies
Cookies允许数据在请求之间持久化。在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 "ru" as the default value
language =cookies->getValue('language', 'ru');
// 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 − 为了看到发送cookie的效果,在 SiteController 中创建一个名为 actionSendCookies 的方法。
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' => '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
//required by cookie validation
'cookieValidationKey' => 'ymoaYrebZHa8gURuolioHGlK8fLXCKjO',
],**
'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' => [
'hello' => [
'class' => 'app\modules\hello\Hello',
],
],
'params' => params,
]; if (YII_ENV_DEV) { // configuration adjustments for 'dev' environmentconfig['bootstrap'][] = 'debug';
config['modules']['debug'] = [ 'class' => 'yii\debug\Module', ];config['bootstrap'][] = 'gii';
config['modules']['gii'] = [ 'class' => 'yii\gii\Module', ]; } returnconfig;
?>
通过将 yii\web\Request::$enableCookieValidation 属性设置为 false ,您可以禁用cookie验证。