在 SSL (HTTPS) 與非 SSL (HTTP) 之間切換時,Cookie 的 Secure 標記與 Domain 設定不一致,導致 Session ID 無法正確傳遞,使用者出現「登入後立即登出」或「購物車清空」現象。
<?php
// bootstrap.php 或 core.php
Configure::write('Session', [
'defaults' => 'php',
'ini' => [
'session.cookie_secure' => false, // 允許 HTTP 傳送
'session.cookie_httponly' => true, // 防 XSS
'session.cookie_samesite' => 'Lax', // CSRF 保護
'session.cookie_domain' => '.example.com', // 共享主域名
'session.cookie_path' => '/',
],
'cookie' => 'CAKEPHP',
'timeout' => 2880, // 48 小時
]);
<?php
// UsersController::login()
if ($this->Auth->login()) {
$username = $this->request->data['User']['username'];
$password = $this->request->data['User']['password']; // 僅示範,實際不應存明文
// 手動設定跨協議 Cookie
$cookieOptions = [
'expires' => time() + 86400 * 30,
'path' => '/',
'domain' => '.example.com',
'secure' => false, // 允許 HTTP
'httponly' => true,
'samesite' => 'Lax',
];
setcookie('Auth.User.username', $username, $cookieOptions);
// 密碼建議存雜湊或 Token,不存明文
$this->redirect($this->Auth->redirectUrl());
}
session.cookie_secure = trueStrict-Transport-Security: max-age=31536000Configure::write('Session.save', 'redis'); 需安裝 php-redis