setcookie() / $_COOKIE$this->input->set_cookie() / $this->input->cookie()set_cookie() / get_cookie() / delete_cookie()$this->load->helper('cookie');
set_cookie('cookie_name', 'cookie_value', 86400); // 過期時間:秒數(86400=1天)
完整參數:set_cookie($name, $value, $expire, $domain, $path, $prefix, $secure, $httponly)
$value = get_cookie('cookie_name'); // 不存在回傳空字串
delete_cookie('cookie_name');
將常用操作封裝為父類別方法,所有控制器繼承即可複用:
class MY_Controller extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper('cookie');
}
// 設定加密 Cookie(建議儲存敏感資料時使用)
protected function setSecureCookie($name, $value, $expire = 86400) {
$config = &get_config();
$value = $this->encrypt->encode($value); // 需載入 encrypt 類別並設定 encryption_key
set_cookie($name, $value, $expire, $config['cookie_domain'], $config['cookie_path'], $config['cookie_prefix'], true, true);
}
// 讀取並解密
protected function getSecureCookie($name) {
$value = get_cookie($name);
if ($value) {
return $this->encrypt->decode($value);
}
return false;
}
// 一般 Cookie
protected function setCookie($name, $value, $expire = 86400) {
set_cookie($name, $value, $expire);
}
protected function getCookie($name) {
return get_cookie($name);
}
protected function deleteCookie($name) {
delete_cookie($name);
}
}
class Welcome extends MY_Controller {
public function login() {
// 驗證成功後
$userData = ['id' => 123, 'username' => 'john', 'role' => 'admin'];
$this->setSecureCookie('user_session', json_encode($userData), 3600); // 1小時
redirect('dashboard');
}
public function dashboard() {
$session = $this->getSecureCookie('user_session');
if (!$session) {
redirect('login');
}
$user = json_decode($session, true);
$this->load->view('dashboard', ['user' => $user]);
}
public function logout() {
$this->deleteCookie('user_session');
redirect('login');
}
}
$config['cookie_prefix'] = 'myapp_'; // 避免與其他應用衝突 $config['cookie_domain'] = ''; // 跨子域名共享可設 '.example.com' $config['cookie_path'] = '/'; // 整站可用 $config['cookie_secure'] = false; // 僅 HTTPS 傳輸設 true(需 SSL) $config['cookie_httponly'] = true; // 防止 JS 存取(XSS 防護) $config['encryption_key'] = 'your_32_char_random_key'; // 加密金鑰 $config['sess_driver'] = 'files'; // Session 驅動(與 Cookie 區分)
| 特性 | Cookie | Session |
|---|---|---|
| 儲存位置 | 客戶端瀏覽器 | 伺服器(檔案/資料庫/Redis/Memcached) |
| 容量限制 | 約 4KB / 個 | 較大(受伺服器儲存限制) |
| 安全性 | 可被竄改、攔截、XSS 竊取 | 資料不暴露給客戶端,較安全 |
| 跨網域 | 支援(設定 domain) | 需共享 Session 儲存體 |
| 適用場景 | 記住登入、偏好設定、追蹤 ID | 使用者狀態、權限、購物車、敏感資料 |
cookie_httponly=true 防止 XSS 竊取。cookie_secure=true。set_cookie(..., '', '', '', '', '', true, true, 'Lax') 防禦 CSRF。cookie_path 限制在必要路徑、cookie_domain 不要設為主域名除非必要。urlencode() 儲存、urldecode() 讀取,或用 JSON 編碼。cookie_domain='.example.com'(前綴點號)。encryption_key 必須固定、長度足夠、全站一致。善用 Cookie Helper 並封裝至基底控制器,能統一管理 Cookie 策略、提升安全性與開發效率。