首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

CakePHP HTTPS/HTTP 切換導致 Session 遺失解決方案

     編輯:PHP 相關知識

問題成因

在 SSL (HTTPS) 與非 SSL (HTTP) 之間切換時,Cookie 的 Secure 標記與 Domain 設定不一致,導致 Session ID 無法正確傳遞,使用者出現「登入後立即登出」或「購物車清空」現象。

解決方案

方法一:統一 Cookie 參數(推薦)

<?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 小時
]);

方法二:登入成功後手動寫入 Cookie

<?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());
}

方法三:強制全站 HTTPS(根治)

  • 申請有效 SSL 憑證(Let's Encrypt 免費)
  • Nginx/Apache 設定 301 重導向 HTTP → HTTPS
  • session.cookie_secure = true
  • 設定 HSTS 標頭:Strict-Transport-Security: max-age=31536000

多伺服器叢集補充

  • Session 儲存改用資料庫 / Redis / Memcached,避免本機檔案不同步
  • Configure::write('Session.save', 'redis'); 需安裝 php-redis
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved