2013-04-23 43 views
1

我使用稍微修改後的登錄代碼發現here,並且遇到我認爲來自session_set_cookie_params()的行爲,我不明白。session_set_cookie_params()在重定向後設置兩個cookie

我使用會話,cookie和header()將用戶重定向到登錄頁面,然後返回到他們請求的頁面。我的問題是,儘管初始頁面和登錄頁面使用相同的函數來處理會話和cookie,但是正在設置兩個單獨的cookie;一個用於www.example.com,一個用於example.com。這阻止了登錄後在初始頁面上設置的會話變量被讀取。

下面是從任何請求頁面的代碼示例:

requireSSL(); 
sec_session_start(); 
if(login_check($mysqli) == false) { 
    $_SESSION['origURL'] = $_SERVER['REQUEST_URI']; 
    header('Location: https://www.example.com/login.php'); 
    exit(); 
} 

這裏的功能是:

function requireSSL() { 
    if($_SERVER["HTTPS"] != "on") { 
     header("Location: https://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]); 
     exit(); 
    } 
} 

function sec_session_start() { 
    $session_name = 'sec_session_id'; // Set a custom session name 
    $secure = true; // Set to true if using https. 
    $httponly = true; // This stops javascript being able to access the session id. 
    ini_set('session.use_only_cookies', 1); // Forces sessions to only use cookies. 
    $cookieParams = session_get_cookie_params(); // Gets current cookies params. 
    session_set_cookie_params($cookieParams["lifetime"], $cookieParams["path"], $cookieParams["domain"], $secure, $httponly); 
    session_name($session_name); // Sets the session name to the one set above. 
    session_start(); // Start the php session 
    session_regenerate_id(true); // regenerated the session, delete the old one.  
} 

雖然我能夠通過明確說明在域「修復」這一行爲session_set_cookie_params()(例如「example.com」),我會瞭解爲什麼兩個cookie被設置在首位。謝謝!

回答

1

原因:因爲example.com和www.example.com是瀏覽器的兩個不同域。


example.com 

是更高級別的域。

www.example.com 

是較低級域,在example.com

通過Cookie設置到較高的領域:通過

setcookie($name, $value, $expire, $path, 'example.com'); 

也爲會話cookie:

session_set_cookie_params($lifetime, $path, 'example.com'); 

同樣解決了這個問題。

所以他們的有效期爲兩個www.example.com和example.com

看看在PHP手冊域定義setcookie function

警告:高一級域名餅乾有效且可由較低級別的所有頁面訪問。 example.com的Cookie也可從mysubdomain.example.com獲得。

所以,如果不需要,你應該區分cookie域。


恕我直言:

header("Location: https://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]); 

而不是發送的報頭,呼應它,看看到底是怎麼回事......

+0

感謝您的回覆,但我不知道它回答我的問題。我瞭解域和子域的區別,但我不明白爲什麼要設置兩個cookie。我在手冊的setcookie()或session_set_cookie_params()下看不到會導致此行爲的任何內容。例如,設置www.example.com是否也爲example.com設置了一個cookie?那會很奇怪,不需要,也沒有證件。 – Grenoble 2013-04-24 17:16:11

相關問題