2017-04-15 123 views
0

我知道這個問題有很多重複,但我嘗試了其中幾個,沒有一個已經被回答。PHP會話沒有註銷/未設置

這裏是我的logout.php代碼:

<?php 
    session_start(); 
    require './codefiles/dbhelper.php'; 
    $dbh = new DbHelper(); 
    $dbh->Execute('UPDATE surveyors SET LoggedIn=\'0\', SessionID=\'\' WHERE Username=\''.$_SESSION['username'].'\''); 
    session_unset(); 
    session_abort(); 
    session_destroy(); 
    $_SESSION = array(); 
    unset($_SESSION['username']); 
    unset($dbh); 
    header('location:index.php'); 
?> 

但會話變量太「執着」被刪除。會話值不會被清除,會話變量也不會被刪除。對象$ dbh未設置,但未設置$ _SESSION ['username'];

另一個無關的問題,儘管我設置LoggedIn = 0,在我的SQL查詢中,它只是在數據庫中保持爲1。 LoggedIn字段的類型是'位'。 SessionID字段設置爲空白。

有什麼解決方法嗎?

編輯:

移除echo $dbh->error,因爲它是不必要的。

編輯2:

新增session_destroy()通過霍山Magdy建議。

+0

你有沒有試過'session_destroy();'http://php.net/manual/en/function.session-destroy.php? – Hossam

+0

哦,是的。我有。 –

+0

糾正我,如果我錯了。中止會話似乎會關閉會話,從而阻止寫入存儲。我想知道是什麼阻止你使用'session_set_save_handler()'來實現'SessionHandlerInterface'類嗎? – frz3993

回答

0

我不知道爲什麼,但破壞會話的代碼在某種程度上不起作用logout.php。它工作在index.php等文件中,但會出現各種不可預知的行爲。

找到了解決此問題的解決方法。該logout.php有如下代碼:

<?php 
    session_start(); 
    $_SESSION['logout'] = TRUE; 
    header('location:index.php'); 
?> 

而這種代碼添加到的index.php

# Implement logout functionality 
<?php 
    session_start(); 
    if(isset($_SESSION['logout']) && $_SESSION['logout'] == TRUE){ 
     foreach($_SESSION as $var => $value){ 
      unset($_SESSION[$var]); 
     } 
     session_destroy(); 
     session_unset(); 
    } 
?> 

它可能不是一個標準化的解決方案,但這些代碼對我的作品每一次,沒有不可預知的行爲。

感謝大家分享他們的想法。

+0

我想foreach未設置必須在logout.php或login.php之前設置新的會話值,在index.php不工作,因爲我摧毀了我需要的會議。無論如何,這是一個奇怪的問題。你測試了這個http://stackoverflow.com/questions/16759719/i-just-cant-destroy-a-session-in-php? –

+0

正如我所說,我的代碼在任何文件中工作,但不是在我的** logout.php **中(不知道爲什麼)。如果它不適合你,那可能是因爲我們的邏輯不同。任何方式,您建議解決我的另一個問題的鏈接,每次註銷後重新生成一個新的會話ID。謝謝。 –

0
<?php 
include 'codefiles/dbhelper.php'; 

if(!isset($_SESSION['id'])) 
{ 
    header ("Location: login_form.php"); 
} 
else 
{ 
    session_destroy(); 
    die('You have been logged out.<meta http-equiv="refresh" content="0;url=login_form.php">'); 
} 
?> 

這基本上是「註銷」結構。

+0

但'session_destroy()'只是不工作,既不在logout.php也不在任何其他頁面。 –

0

試試這個

<?php 
session_start(); 
require './codefiles/dbhelper.php'; 
$dbh = new DbHelper(); 
$dbh->Execute('UPDATE surveyors SET LoggedIn=\'0\', SessionID=\'\' WHERE Username=\''.$_SESSION['username'].'\''); 

echo session_status() . '<br />'; 

session_unset();  
session_destroy(); 

echo session_status(); 

// header('location:index.php'); 

讓我們來看看session_status()說。 但我的項目未設置& &銷燬工作。

+0

儘管我使用session_start(),調用'session_destroy()'會拋出警告,如下所示:* Warning:session_destroy():嘗試銷燬C:\ xampp \ htdocs \ xxxxxxxxx \ index.php *中的未初始化會話。關於'echo session_status()',它打印** 1 **。 –

+0

session_status第一次,第二次還是兩者都返回1?根據http://php.net/manual/es/function.session-status.php 1表示沒有活動會話。 –

+0

在'session_unset()'和'session_destroy()'返回** 2 **之前調用'session_status()',之後返回** 1 **。然後調用'print_r($ _ SESSION);'打印會話中的所有變量。 –