簡體   English   中英

跨子域的PHP會話

[英]PHP Session Across Subdomains

我有一個在Azure上運行的PHP 7應用程序,其中客戶端在該應用程序的多個子域之間移動,但訪問同一網站。 子域區分公司,一個用戶與多個公司相關聯。 使用Cookie跨這些域跟蹤用戶的信息。

我的問題是,盡管有相同的Cookie ID存在於兩個子域,如果我存儲在信息上的cookie a.example.com ,然后加載相同的網頁和Cookie b.example.com ,它並沒有顯示信息。 內聯與SO以前的答案,我設置的cookie的有效期為/.example.com

我確實為我的應用程序打開了實例縮放功能,並認為可能是導致問題的原因,所以我將其關閉了。 但是即使有一個實例,Azure仍然有兩個不同的主機來服務對不同域的請求-盡管相同的實例因此應該是相同的共享會話。

我在頁面上使用以下代碼,在兩個子域上訪問該頁面,該頁面應打印出我使用cookie訪問過的所有子域,但僅顯示當前域。

$currentCookieParams = session_get_cookie_params();

$serverParts = explode('.', $_SERVER['HTTP_HOST']);
$serverPartsCount = sizeof($serverParts);

session_set_cookie_params(
    time() + 315360000, //(10 * 365 * 24 * 60 * 60),
    '/',
    '.'.$serverParts[$serverPartsCount-2].'.'.$serverParts[$serverPartsCount-1], //equates to '.mydomain.com'
    TRUE,
    $currentCookieParams["httponly"]
);

session_start();

//use an array to track every subdomain we visit with this cookie
if (!isset($_SESSION['visitedDomains']))
{
    $_SESSION['visitedDomains'] = [];
}
$_SESSION['visitedDomains'][$_SERVER['HTTP_HOST']] = 'visited';

//show the cookie id
var_dump(session_id());
echo '<br><br>';

//the hostname of the machine serving this request
var_dump(gethostname());
echo '<br><br>';

//what should be a list of all domains visited using this cookie
var_dump($_SESSION['visitedDomains']);
echo '<br><br>';

//cookie params
var_dump(session_get_cookie_params());

您需要將session.cookie_secure設置為FLASE 使其如下所示:

session_set_cookie_params(
    time() + 315360000, //(10 * 365 * 24 * 60 * 60),
    '/',
    '.'.$serverParts[$serverPartsCount-2].'.'.$serverParts[$serverPartsCount-1], //equates to '.mydomain.com'
    FLASE,
    $currentCookieParams["httponly"]
);

這對我來說可以:

在此處輸入圖片說明

我正在使用以下代碼:

<?php

$currentCookieParams = session_get_cookie_params();

$serverParts = explode('.', $_SERVER['HTTP_HOST']);
$serverPartsCount = sizeof($serverParts);

echo '.'.$serverParts[$serverPartsCount-2].'.'.$serverParts[$serverPartsCount-1];
echo '<br><br>';

session_set_cookie_params(
    time() + 315360000, //(10 * 365 * 24 * 60 * 60),
    '/',
    '.'.$serverParts[$serverPartsCount-2].'.'.$serverParts[$serverPartsCount-1], //equates to '.mydomain.com'
    FALSE,
    $currentCookieParams["httponly"]
);

session_start();

//use an array to track every subdomain we visit with this cookie
if (!isset($_SESSION['visitedDomains']))
{
    $_SESSION['visitedDomains'] = [];
}

$_SESSION['visitedDomains'][$_SERVER['HTTP_HOST']] = 'visited';

//show the cookie id
var_dump(session_id());
echo '<br><br>';

//the hostname of the machine serving this request
var_dump(gethostname());
echo '<br><br>';

//what should be a list of all domains visited using this cookie
var_dump($_SESSION['visitedDomains']);
echo '<br><br>';

//cookie params
var_dump(session_get_cookie_params());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM