2012-06-14 21 views
0

我一直在尋找在我正在開發的登錄類中使用session_regenerate_id,並從閱讀PHP文檔和其他一些網站看來,它創建了一個新的會話,之前的數據,因爲該函數是在PHP 4.3.2中添加的。session_generaterate_id PHP 5.1之前

自PHP 5.1起,它有一個delete_old_session參數,如果設置爲true,它也會銷燬前一個會話,但在以前的版本中它不會。

我的問題是,如果我要在運行PHP版本低於5.1的服務器上使用session_regenerate_id,那麼使用session_regenerate_id和銷燬先前會話的最佳方式是什麼?

我不認爲session_destroy()會起作用,因爲如果我在session_regenerate_id之前使用它,那麼它將無法傳遞前一個會話數據,並且在它之後使用它將會破壞新會話。

回答

1

這應該解決您的問題:

session_start(); 
// gets current (previous) session 
$previousID = session_id(); 
session_regenerate_id(); 
// get the new session id 
$newID = session_id(); 
// close session related files 
session_write_close(); 

// set the old session id 
session_id($previousID); 
// start the old session 
session_start(); 
// clear the old session 
session_destroy(); 
// save the old session state (destroyed session) 
session_write_close(); 

// set the regenerated session id 
session_id($newID); 
// start the new session 
session_start(); 

現在你的舊的會話數據被刪除,並轉移到新的會話ID。

+0

非常感謝您的支持,非常高興在所有新版本的PHP中都不會過多地生成新的會話ID並銷燬前一個會話ID。 再次感謝。 –