<?php
// login.php 設置 Cookie
setcookie('token', 'abc123', time() + 86400); // 缺少 path 參數
// 用戶跳轉到 /dashboard/index.php
// $_COOKIE['token'] 為空!
PHP setcookie() 第 4 參數 path 默認為 設置 Cookie 的腳本所在目錄。
login.php 在根目錄 / → Cookie path = / → 全站可訪問 ✅auth/login.php 在 /auth/ → Cookie path = /auth/ → 其他目錄(如 /dashboard/)無法讀取 ❌<?php
// 任意目錄下設置,全站生效
setcookie('token', 'abc123', [
'expires' => time() + 86400,
'path' => '/', // 關鍵:根路徑
'domain' => '', // 當前域,可改為 '.example.com' 支援子域
'secure' => true, // 僅 HTTPS
'httponly'=> true, // 防 XSS
'samesite'=> 'Lax', // CSRF 防護
]);
| Path 值 | 生效範圍 | 典型場景 |
|---|---|---|
| / | 整個域名下所有路徑 | 通用業務 Cookie(登錄態、偏好設置) |
| /admin/ | /admin/ 及其子目錄 | 後台專用 Cookie,前台不可讀 |
| /api/v1/ | 特定 API 版本路徑 | 版本隔離的 Token |
| (默認) | 當前腳本所在目錄 | 極易導致跨目錄失效,不推薦依賴默認值 |
// 主域 example.com 設置,支援 www.example.com、api.example.com、app.example.com
setcookie('sso_token', $token, [
'expires' => time() + 2592000,
'path' => '/',
'domain' => '.example.com', // 關鍵:以點開頭
'secure' => true,
'httponly'=> true,
'samesite'=> 'None', // 跨站請求需攜帶,配合 Secure
]);
注意:SameSite=None 必須配合 Secure,否則瀏覽器拒絕設置。
Path、Domain、Expires 欄位。var_dump($_COOKIE) 確認接收情況。setcookie 導致參數丟失。<?php
// Laravel
Cookie::queue('token', $token, 1440, '/', null, true, true, false, 'Lax');
// ThinkPHP 6+
Cookie::set('token', $token, ['expire' => 86400, 'path' => '/', 'secure' => true, 'httponly' => true, 'samesite' => 'Lax']);
// Symfony
$response->headers->setCookie(new Cookie('token', $token, time()+86400, '/', '', true, true, false, 'Lax'));