[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數據,如數字或小字符串文字。
- 常規
- Welcome
- 貢獻
- 生成回溯
- 測試重現
- 單元測試
- 入門
- 安裝
- Web服務器設置
- WAMP
- XAMPP
- 教程
- 基礎教程
- 教程:創建一個簡單的REST API
- 教程:V?kuró
- 提升性能
- 教程:INVO
- 開發環境
- Phalcon Compose (Docker)
- Nanobox
- Phalcon Box (Vagrant)
- 開發工具
- Phalcon開發者工具的安裝
- Phalcon開發者工具的使用
- 調試應用程序
- 核心
- MVC應用
- 微應用
- 創建命令行(CLI)應用程序
- 依賴注入與服務定位
- MVC架構
- 服務
- 使用緩存提高性能
- 讀取配置
- 上下文轉義
- 類加載器
- 使用命名空間
- 日志
- 隊列
- 數據庫
- 數據庫抽象層
- Phalcon查詢語言(PHQL)
- ODM(對象文檔映射器)
- 使用模型
- 模型行為
- ORM緩存
- 模型事件
- 模型元數據
- 模型關系
- 模型事務
- 驗證模型
- 數據庫遷移
- 分頁
- 前端
- Assets管理
- 閃存消息
- 表單
- 圖像
- 視圖助手(標簽)
- 使用視圖
- Volt:模板引擎
- 業務邏輯
- 訪問控制列表(ACL)
- 注解解析器
- 控制器
- 調度控制器
- 事件管理器
- 過濾與清理
- 路由
- 在session中存儲數據
- 生成URL和路徑
- 驗證
- HTTP
- Cookies管理
- 請求環境
- 返回響應
- 安全
- 加密/解密
- 安全
- 國際化
- 國際化
- 多語言支持