2010-10-16 40 views
30

是否足以的最佳方式 - 即使瀏覽器沒有關閉

session_start(); // Must start a session before destroying it 

if (isset($_SESSION)) 
{ 
    unset($_SESSION); 
    session_unset(); 
    session_destroy(); 
} 
當用戶從菜單中選擇 Log out

,但不會放棄他的瀏覽器?我想徹底刪除會話的所有生存和$_SESSION

+4

我不會'未設置($ _ SESSION);''之前session_destroy()',它可能是session_destroy無法正常工作 – 2010-10-16 09:21:30

回答

60

按照manual,還有更多的工作要做:

爲了完全終止會話,想註銷用戶,會話ID也必須取消設置。如果使用cookie傳播會話標識(默認行爲),則必須刪除會話cookie。 setcookie()可用於此目的。

手動鏈接有一個完整的工作示例如何做到這一點。從那裏偷來的:

<?php 
// Initialize the session. 
// If you are using session_name("something"), don't forget it now! 
session_start(); 

// Unset all of the session variables. 
$_SESSION = array(); 

// If it's desired to kill the session, also delete the session cookie. 
// Note: This will destroy the session, and not just the session data! 
if (ini_get("session.use_cookies")) { 
    $params = session_get_cookie_params(); 
    setcookie(session_name(), '', time() - 42000, 
     $params["path"], $params["domain"], 
     $params["secure"], $params["httponly"] 
    ); 
} 

// Finally, destroy the session. 
session_destroy(); 
?> 
+6

爲什麼不使用'session_unset',而不是'$ _SESSION = array();'? – alexw 2016-06-04 01:47:19

+0

我在這裏測試過,你可以使用unset($ _ SESSION)或者將null分配給$ _SESSION或者像Pekka這樣的空數組! – Zanoldor 2017-01-13 15:50:46