2.27 Cookies Management
cooke管理
Cookies
are very useful way to store small pieces of data in the client that can be retrieved even if the user closes his/her browser.Phalcon\Http\Response\Cookiesacts
as a global bag for cookies. Cookies are stored in this bag during the request execution and are sent automatically at the end of the request.
cookie非常有,常用来在客户端存储小数据,甚至用户关闭了浏览器亦即取到数据。Phalcon\Http\Response\Cookies是一个cookie全局包装器。cookie保存在这个包装类中,在请求执行时,数据会被自动发送。
2.27.1 Basic Usage
基本使用
You can set/get cookies by just accessing the ‘cookies’ service in any part of the application where services can be accessed:
我们可以在应用的任何可以使用服务的地方设置或取cookie:
<?php
class
SessionControllerextends
Phalcon\Mvc\Controller
{
public function
loginAction()
{
//Check if the cookie has previously set
if
($this->cookies->has(’remember-me’))
{//判断是否存在键
//Get the cookie
$rememberMe
=$this->cookies->get(’remember-me’);//取cookie对象
//Get the cookie’s value
$value =$rememberMe->getValue();//取键值
}
}
public function
startAction()
{
$this->cookies->set(’remember-me’,’some
value’,time()+
15*
86400);//设置键值
}
}
2.27.2 Encryption/Decryption of Cookies
加密解密码cookie
By default, cookies are automatically encrypted before be sent to the client and decrypted when retrieved. This protection allow
unauthorized users to see the cookies’ contents in the client (browser). Although this protection, sensitive data should not be stored on cookies.
You can disable encryption in the following way:
默认情况下,cookie会被加密,cookie在保存时进行加密,在取值是解密。当然非授权用户可以看到加密过的密文的。尽管已经加密但还是最好不要保存敏感的信息在cookie中。可以使用下面的方式禁用加密。
<?php
$di->set(’cookies’,function()
{
$cookies
=new
Phalcon\Http\Response\Cookies();
$cookies->useEncryption(false);//禁用加密
return
$cookies;
});
In case of using encryption a global key must be set in the ‘crypt’ service:
<?php
$di->set(’crypt’,function()
{
$crypt
=new
Phalcon\Crypt();
$crypt->setKey(’#1dj8$=dp?.ak//j1V$’);//设置私有加密键
return $crypt;
});
Send cookies data without encryption to clients including complex objects structures, resultsets, service
information, etc. could expose internal application details that could be used by an attacker to attack the
application. If you do not want to use encryption, we highly recommend you only send very basic cookie
data like numbers or small string literals.
把一些复杂的对象,结构,服务信息或结果等未经加密保存在cookie中会有暴露应用实现细节的危险,这会给骇客以攻击的机会。如果你不想对cookie加密,我们强烈建议你只保存简单的数据,比如数字或字符串等。