


Analyze related operations of cookie and session functions in PHP's Yii framework, yiicookie_PHP tutorial
Analyze related operations of cookie and session functions in PHP's Yii framework, yiicookie
Sessions
Similar to requests and responses, sessions can be accessed by default through the session application component of the yiiwebSession instance.
Open and close Sessions
You can use the following code to open and close the session.
$session = Yii::$app->session; // 检查session是否开启 if ($session->isActive) ... // 开启session $session->open(); // 关闭session $session->close(); // 销毁session中所有已注册的数据 $session->destroy();
Calling the yiiwebSession::open() and yiiwebSession::close() methods multiple times will not cause an error, because the method will first check whether the session is open.
Access Session Data
To access the data stored in session, you can do the following:
$session = Yii::$app->session; // 获取session中的变量值,以下用法是相同的: $language = $session->get('language'); $language = $session['language']; $language = isset($_SESSION['language']) ? $_SESSION['language'] : null; // 设置一个session变量,以下用法是相同的: $session->set('language', 'en-US'); $session['language'] = 'en-US'; $_SESSION['language'] = 'en-US'; // 删除一个session变量,以下用法是相同的: $session->remove('language'); unset($session['language']); unset($_SESSION['language']); // 检查session变量是否已存在,以下用法是相同的: if ($session->has('language')) ... if (isset($session['language'])) ... if (isset($_SESSION['language'])) ... // 遍历所有session变量,以下用法是相同的: foreach ($session as $name => $value) ... foreach ($_SESSION as $name => $value) ...
When the session data is an array, the session component will restrict you from directly modifying the unit items in the data, for example:
$session = Yii::$app->session; // 如下代码不会生效 $session['captcha']['number'] = 5; $session['captcha']['lifetime'] = 3600; // 如下代码会生效: $session['captcha'] = [ 'number' => 5, 'lifetime' => 3600, ]; // 如下代码也会生效: echo $session['captcha']['lifetime'];
$session = Yii::$app->session; // 直接使用$_SESSION (确保Yii::$app->session->open() 已经调用) $_SESSION['captcha']['number'] = 5; $_SESSION['captcha']['lifetime'] = 3600; // 先获取session数据到一个数组,修改数组的值,然后保存数组到session中 $captcha = $session['captcha']; $captcha['number'] = 5; $captcha['lifetime'] = 3600; $session['captcha'] = $captcha; // 使用ArrayObject 数组对象代替数组 $session['captcha'] = new \ArrayObject; ... $session['captcha']['number'] = 5; $session['captcha']['lifetime'] = 3600; // 使用带通用前缀的键来存储数组 $session['captcha.number'] = 5; $session['captcha.lifetime'] = 3600;
Customized Session Storage
The yiiwebSession class stores session data as files on the server by default. Yii provides the following session classes to implement different session storage methods:
- yiiwebDbSession: Store session data in the data table
- yiiwebCacheSession: Stores session data in the cache. The cache is related to the cache component in the configuration
- yiiredisSession: Store session data in redis as the storage medium
- yiimongodbSession: Store session data in MongoDB.
Note: If you access a session using a custom storage medium through $_SESSION, you need to ensure that the session has been opened using yiiwebSession::open(). This is because the custom session storage processor is registered in this method.
To learn how to configure and use these component classes, please refer to their API documentation. The following is an example showing how to configure yiiwebDbSession in the application configuration to use the data table as the session storage medium.
return [ 'components' => [ 'session' => [ 'class' => 'yii\web\DbSession', // 'db' => 'mydb', // 数据库连接的应用组件ID,默认为'db'. // 'sessionTable' => 'my_session', // session 数据表名,默认为'session'. ], ], ];
CREATE TABLE session ( id CHAR(40) NOT NULL PRIMARY KEY, expire INTEGER, data BLOB )
- MySQL: LONGBLOB
- PostgreSQL: BYTEA
- MSSQL: BLOB
Flash data
Flash data is a special kind of session data. Once it is set in a request, it will only be valid in the next request, and then the data will be automatically deleted. It is often used to implement information that only needs to be displayed to the end user once, such as displaying confirmation information after the user submits a form.Session can be set or accessed through the session application component, for example:
$session = Yii::$app->session; // 请求 #1 // 设置一个名为"postDeleted" flash 信息 $session->setFlash('postDeleted', 'You have successfully deleted your post.'); // 请求 #2 // 显示名为"postDeleted" flash 信息 echo $session->getFlash('postDeleted'); // 请求 #3 // $result 为 false,因为flash信息已被自动删除 $result = $session->hasFlash('postDeleted');
When calling yiiwebSession::setFlash(), any existing data with the same name will be automatically overwritten. To append data to the existing flash with the same name, you can call yiiwebSession::addFlash() instead. For example:
$session = Yii::$app->session; // 请求 #1 // 在名称为"alerts"的flash信息增加数据 $session->addFlash('alerts', 'You have successfully deleted your post.'); $session->addFlash('alerts', 'You have successfully added a new friend.'); $session->addFlash('alerts', 'You are promoted.'); // 请求 #2 // $alerts 为名为'alerts'的flash信息,为数组格式 $alerts = $session->getFlash('alerts');
Cookies
Read Cookies
The currently requested cookie information can be obtained through the following code:
// 从 "request"组件中获取cookie集合(yii\web\CookieCollection) $cookies = Yii::$app->request->cookies; // 获取名为 "language" cookie 的值,如果不存在,返回默认值"en" $language = $cookies->getValue('language', 'en'); // 另一种方式获取名为 "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')) ... if (isset($cookies['language'])) ...
Send Cookies
You can send cookies to end users using the following code: You can use the following code to send cookies to end users:
// 从"response"组件中获取cookie 集合(yii\web\CookieCollection) $cookies = Yii::$app->response->cookies; // 在要发送的响应中添加一个新的cookie $cookies->add(new \yii\web\Cookie([ 'name' => 'language', 'value' => 'zh-CN', ])); // 删除一个cookie $cookies->remove('language'); // 等同于以下删除代码 unset($cookies['language']);
注意: 为安全起见yii\web\Cookie::httpOnly 被设置为true,这可减少客户端脚本访问受保护cookie(如果浏览器支持)的风险, 更多详情可阅读 httpOnly wiki article for more details.
Cookie验证
在上两节中,当通过request 和 response 组件读取和发送cookie时,你会喜欢扩展的cookie验证的保障安全功能,它能 使cookie不被客户端修改。该功能通过给每个cookie签发一个哈希字符串来告知服务端cookie是否在客户端被修改, 如果被修改,通过request组件的yii\web\Request::cookiescookie集合访问不到该cookie。
注意: Cookie验证只保护cookie值被修改,如果一个cookie验证失败,仍然可以通过$_COOKIE来访问该cookie, 因为这是第三方库对未通过cookie验证自定义的操作方式。
Cookie验证默认启用,可以设置yii\web\Request::enableCookieValidation属性为false来禁用它,尽管如此,我们强烈建议启用它。
注意: 直接通过$_COOKIE 和 setcookie() 读取和发送的Cookie不会被验证。
当使用cookie验证,必须指定yii\web\Request::cookieValidationKey,它是用来生成s上述的哈希值, 可通过在应用配置中配置request 组件。
return [ 'components' => [ 'request' => [ 'cookieValidationKey' => 'fill in a secret key here', ], ], ];
补充: yii\web\Request::cookieValidationKey 对你的应用安全很重要, 应只被你信任的人知晓,请不要将它放入版本控制中。
您可能感兴趣的文章:
- PHP的Yii框架中行为的定义与绑定方法讲解
- 详解在PHP的Yii框架中使用行为Behaviors的方法
- 深入讲解PHP的Yii框架中的属性(Property)
- 解读PHP的Yii框架中请求与响应的处理流程
- PHP的Yii框架中使用数据库的配置和SQL操作实例教程
- 实例讲解如何在PHP的Yii框架中进行错误和异常处理
- 简要剖析PHP的Yii框架的组件化机制的基本知识
- PHP的Yii框架中YiiBase入口类的扩展写法示例
- 详解PHP的Yii框架的运行机制及其路由功能
- 深入解析PHP的Yii框架中的event事件机制
- 全面解读PHP的Yii框架中的日志功能
- PHP的Yii框架中移除组件所绑定的行为的方法

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.
