企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
[TOC] # Cookies管理 [Cookies](http://en.wikipedia.org/wiki/HTTP_cookie) 是在客户端计算机上存储小块数据的非常有用的方法,即使用户关闭他/她的浏览器也可以检索这些数据。`Phalcon\Http\Response\Cookies` a充当cookie的全局包。Cookie在请求执行期间存储在此包中,并在请求结束时自动发送。 ## 基本用法 您可以通过访问可以访问服务的应用程序的任何部分中的`cookie`服务来设置/获取cookie: ```php <?php use Phalcon\Mvc\Controller; class SessionController extends Controller { public function loginAction() { // Check if the cookie has previously set if ($this->cookies->has('remember-me')) { // Get the cookie $rememberMeCookie = $this->cookies->get('remember-me'); // Get the cookie's value $value = $rememberMeCookie->getValue(); } } public function startAction() { $this->cookies->set( 'remember-me', 'some value', time() + 15 * 86400 ); $this->cookies->send(); } public function logoutAction() { $rememberMeCookie = $this->cookies->get('remember-me'); // Delete the cookie $rememberMeCookie->delete(); } } ``` ## Cookie的加密/解密 默认情况下,cookie在发送到客户端之前会自动加密,并在从用户检索时解密。此保护可防止未经授权的用户在客户端(浏览器)中查看cookie的内容。尽管有这种保护,敏感数据不应存储在cookie中。 您可以按如下方式禁用加密: ```php <?php use Phalcon\Http\Response\Cookies; $di->set( 'cookies', function () { $cookies = new Cookies(); $cookies->useEncryption(false); return $cookies; } ); ``` 如果要使用加密,则必须在加密服务中设置全局密钥: ```php <?php use Phalcon\Crypt; $di->set( 'crypt', function () { $crypt = new Crypt(); /** * Set the cipher algorithm. * * The `aes-256-gcm' is the preferable cipher, but it is not usable until the * openssl library is upgraded, which is available in PHP 7.1. * * The `aes-256-ctr' is arguably the best choice for cipher * algorithm in these days. */ $crypt->setCipher('aes-256-ctr'); /** * Setting the encryption key. * * The key should have been previously generated in a cryptographically safe way. * * Bad key: * "le password" * * Better (but still unsafe): * "#1dj8$=dp?.ak//j1V$~%*0X" * * Good key: * "T4\xb1\x8d\xa9\x98\x054t7w!z%C*F-Jk\x98\x05\\\x5c" * * Use your own key. Do not copy and paste this example key. */ $key = "T4\xb1\x8d\xa9\x98\x054t7w!z%C*F-Jk\x98\x05\\\x5c"; $crypt->setKey($key); return $crypt; } ); ``` >[danger] 向客户端发送不加密的cookie数据(包括复杂对象结构,结果集,服务信息等)可能会暴露攻击者可能用来攻击应用程序的内部应用程序详细信息。如果您不想使用加密,我们强烈建议您只发送非常基本的cookie数据,如数字或小字符串文字。