2012-03-28 22 views
1

我需要設置一個非常短的會話(3分鐘),當我的網站上的特定頁面。如果有人在3分鐘的會話中再次點擊該頁面,會話應該更新爲從此時起3分鐘。Zend_Session和過期

在我的「引導」(這不是一個典型的Zend的引導,但它包含在每一頁),我做到以下幾點:

$aSessionSaveHandlerConfig = array 
(
    "name"   => "Sessions", 
    "primary"  => "Session_ID", 
    "modifiedColumn" => "UpdateTimestamp", 
    "dataColumn"  => "Data", 
    "lifetimeColumn" => "Lifetime", 
); 

$oSaveHandler = new Zend_Session_SaveHandler_DbTable($aSessionSaveHandlerConfig); 
$oSaveHandler->setLifetime(App::$ReservationTimeout)->setOverrideLifetime(true);  

Zend_Session::setSaveHandler($oSaveHandler); 

ini_set("session.cookie_lifetime",App::$ReservationTimeout); 

$aSessionOptions = array 
(
    "gc_probability" => 100, 
    "gc_divisor"  => 100, 
    "gc_maxlifetime" => App::$ReservationTimeout, 
    "cookie_lifetime" => App::$ReservationTimeout, 
); 

Zend_Session::setOptions($aSessionOptions); 

那麼應該創建一個內頁/更新會議上,我有:

App::$ReservationSession = new Zend_Session_Namespace("ReservationSession"); 
$oSaveHandler = Zend_Session::getSaveHandler(); 
$oSaveHandler->setLifetime(App::$ReservationTimeout); 

我看到在數據庫中的記錄,壽命列是正確的,但如果我屢創創建/更新會話頁面時,我得到一個新的會話ID3分鐘過後(另一個在垃圾回收後被移除。

看來問題是讓cookie更新它的時間。有任何想法嗎?

回答

3

要獲得會話cookie以更新其到期時間,您可以使用Zend_Session::rememberMe()更改Cookie的默認生存期。調用rememberMe()還會導致Zend_Session::regenerateId()被調用,它將生成新的會話ID,將舊會話數據複製到新會話,並向瀏覽器發送新的會話cookie。

嘗試下面的代碼,看看它是否解決您的問題:

App::$ReservationSession = new Zend_Session_Namespace("ReservationSession"); 
$oSaveHandler = Zend_Session::getSaveHandler(); 
$oSaveHandler->setLifetime(App::$ReservationTimeout); 

// Call remember me which will send a new session cookie with 3 minute expiration 
// from the current time. Old session data is copied to the new one and the old 
// session is deleted 
Zend_Session::rememberMe(App::$ReservationTimeout); 

參見Session Identifiers手冊部分獲取更多信息,或另見How to reset a Zend rememberMe function on each automatic login?

UPDATE: 考慮您的意見,我想出了可以使用的解決方案。

這樣做就是照常開始會話,然後檢查會話中的值以查看用戶是否有現有會話。

如果他們確實有會話,它將使用setcookie()使用現有參數(包括會話ID)發送更新的會話cookie,但將過期設置爲time() + $ReservationTimeout。如果他們沒有會話,則不需要更新cookie,因爲到期已經是正確的,並且將在他們的下一個請求(假設他們在到期之前訪問)時更新。

App::$ReservationSession = new Zend_Session_Namespace("ReservationSession"); 
$oSaveHandler = Zend_Session::getSaveHandler(); 
$oSaveHandler->setLifetime(App::$ReservationTimeout); 

if (!isset(App::$ReservationSession->hasSession)) { 
    // user had no session before or it was expired 
    App::$ReservationSession->hasSession = true; 
} else { 
    // user has a valid session, update the cookie to expire 3 mins from now 
    $params = session_get_cookie_params(); 
    $expire = time() + App::$ReservationTimeout; 

    setcookie(session_name(), 
       Zend_Session::getId(), 
       $expire, 
       $params['path'], 
       $params['domain'], 
       $params['secure'], 
       $params['httponly']); 
} 

我測試使用的文件的會話處理器的解決方案,它的工作如預期,我覺得應該是罰款您的情況也是如此。

+0

非常好的解釋,但我有使用會話ID的MySQL InnoDB外鍵約束,因此在更新超時時需要保留相同的會話ID。記憶Me可以做什麼,而無需更改會話ID? – Travis 2012-03-28 21:19:29

相關問題