setcookie() 是 PHP 設定 Cookie 的核心函式,必須在任何輸出之前呼叫(含空白字元、BOM)。掌握六個參數用法,才能精準控制 Cookie 生命週期、作用域與安全性。
setcookie(string $name, string $value = "", int $expire = 0, string $path = "", string $domain = "", bool $secure = false, bool $httponly = false): bool
注意:PHP 7.3+ 新增 $options 陣列寫法,建議新專案改用關聯陣列語法:
setcookie('webURL', 'www.example.com', [
'expires' => time() + 86400,
'path' => '/',
'domain' => '.example.com',
'secure' => true,
'httponly' => true,
'samesite' => 'Lax',
]);
| 參數 | 必要性 | 說明 | 範例值 |
|---|---|---|---|
name | 必填 | Cookie 名稱,勿包含分號、逗號、空白、等號 | user_id |
value | 必填 | Cookie 值,自動 urlencode,取時自動 urldecode | 12345 |
expire | 選填 | Unix 時間戳,0 或省略 = 瀏覽器關閉即失效(Session Cookie) | time() + 3600*24(1 天) |
path | 選填 | Cookie 生效路徑,/ 表全站,/admin/ 僅後台 | / |
domain | 選填 | 生效域名,.example.com 含所有子域,example.com 僅主域 | .example.com |
secure | 選填 | true 僅 HTTPS 傳輸,生產環境務必開啟 | true |
httponly | 選填 | true 禁止 JavaScript 存取,防禦 XSS 竊取 Cookie | true |
samesite | 選填 | PHP 7.3+,Lax / Strict / None,CSRF 防護關鍵 | Lax |
setcookie('remember_token', $token, [
'expires' => time() + 86400 * 30,
'path' => '/',
'domain' => '.mysite.com',
'secure' => true,
'httponly' => true,
'samesite' => 'Lax',
]);
setcookie('admin_sid', $sid, [
'expires' => 0, // 關閉瀏覽器即失效
'path' => '/admin/',
'secure' => true,
'httponly' => true,
]);
setcookie('user_pref', '', [
'expires' => time() - 3600,
'path' => '/',
'domain' => '.mysite.com',
]);
echo、HTML、空白行、BOM 都會導致 Headers already sent 警告。.example.com(前置點)可共享給 www.example.com、api.example.com;不加點則僅限精確匹配。SameSite=None 則 必須 Secure=true,否則瀏覽器會拒絕設定。path=/app 時,/app/ 及 /app/sub 可讀,但 /apple 也會匹配(前綴匹配),建議以 / 結尾。<?php
// 設定
setcookie('test', 'hello', time()+3600, '/');
// 讀取
var_dump($_COOKIE['test'] ?? '未設定');
?>
掌握參數細節,Cookie 管理才能既安全又靈活。