2010-08-18 80 views
30

我已經閱讀了許多用於註銷腳本的php教程,我在想什麼可以從會話中註銷的正確方法!從PHP中的會話中註銷的正確方法

腳本1

<?php 
session_start(); 
session_destroy(); 
header("location:index.php"); 
?> 

腳本2

<?php 
session_start(); 
session_unset(); 
session_destroy(); 
header("location:index.php"); 
?> 

腳本3

<?php 
session_start(); 
if (isset($_SESSION['username'])) 
{ 
    unset($_SESSION['username']); 
} 
header("location:index.php"); 
?> 

有沒有做到這一點任何更有效的方法?會話總是可以通過重新登錄創建,所以我應該使用session_destroy()並使用unset($ _ SESSION ['variable'])來代替?上述3個腳本中哪一個更優選?

+0

記住你想退出()頭重定向後,以避免暴露可能追隨內容... – Julix 2017-06-20 02:13:06

回答

55

session_destroy()頁面中PHP manual

<?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(); 
?> 
+0

謝謝!這非常有用。 – Woppi 2010-12-08 07:14:44

+0

可以解釋這部分嗎? ''[「path」],$ params [「domain」],$ params [「secure」],$ params [「httponly」]);'。我沒有明白你在這裏做什麼 – 2017-12-25 19:29:38

4

Session_unset();只銷毀會話變量。要結束會話,還有另一個功能叫做session_destroy();,它也破壞了會話。

更新:

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

+3

'session_destroy()'不接觸cookie。從文檔:'爲了完全消滅會話,就像登錄用戶一樣,會話ID也必須未被設置。如果使用cookie傳播會話標識(默認行爲),則必須刪除會話cookie。 setcookie()可以用於那個.' http://us3.php.net/manual/en/function.session-destroy.php – ircmaxell 2010-08-18 13:26:53

+0

謝謝ircmaxell – 2010-08-18 13:27:56

9

就個人而言,我執行以下操作:

session_start(); 
setcookie(session_name(), '', 100); 
session_unset(); 
session_destroy(); 
$_SESSION = array(); 

這樣一來,它殺死的餅乾,會破壞內部存儲的所有數據,並銷燬的會話信息的當前實例(這是由session_destroy忽略)。

+1

does setcookie(session_name(),'',100);發佈者@ircmaxell比@Frxstrem發佈的代碼具有更好的行爲? – 2010-08-18 13:37:56

+2

@ Frxstrem的解決方案更加完整(因爲它考慮了所使用的確切cookie參數)。用那個來代替... – ircmaxell 2010-08-18 13:39:33

+0

哦!我明白了:) – 2010-08-18 13:42:18