2013-12-11 28 views
1

我希望能夠捕獲PHP中創建會話時的錯誤。我的主要目標是能夠知道導致問題的原因。是否因爲我們沒有權限訪問寫入會話的文件夾,或者因爲我們沒有可用磁盤空間。在PHP中捕獲會話創建錯誤

所以我們當然會從這開始。

session_start();

,並從這個職位Check if session is set or not, and if not create one?我也嘗試添加

if(session_id() == '') 
{ 
     // session has NOT been started 
     session_start(); 
     echo "Session is started"; 

} 
else 
{ 
     // session has been started 
} 

,並通過使用此命令

測試這個我已經刪除在/ tmp /爲組寫權限和其他

chmod 755 tmp/

但基於我的測試,我仍然看到會話是開始d。有趣的是我可以登錄,但是當我嘗試註銷時,我無法登錄。

關於如何正確獲取會話創建錯誤的原因的任何見解都會大大增強。謝謝!

編輯:

我已經試過弗雷德裏克的建議,並做到了這一點。

try{ 
    // Start session 
    session_start(); 
    echo "Session started. " . session_id(); 
}catch(Exception $e){ 
    echo "Session not started. " . $e->getMessage(); 
} 

但我還是看到這個

會議開始。 fa505cbf4b232773669008495fd08b9f

即使我已經刪除了對/ tmp的寫入權限。看起來try try無法正確地解決問題。

+0

在更改寫入權限之前會話是否存在?當你試圖註銷時,你沒有權限? –

+0

我確實通過退出權限來刪除會話。我也在/ tmp /中刪除會話文件以確保。 我遇到了無法退出寫入權限時無法註銷的情況。 – rccoros

+0

好吧,要獲得異常消息,我將使用try catch塊並打印錯誤。這裏是更多關於例外handeling:http://www.w3schools.com/php/php_exception.asp –

回答

0

隨着弗雷德裏克的建議,檢查/ tmp中確實有我能決定檢查用戶名和密碼之前,只是檢查寫權限和磁盤空間的寫權限。所以我寫了這個代碼

if (is_writable(session_save_path())){ 
    if ($diskfree is <= 0){ 

     // check for authentication here 

    }else{ 
     header("Location: login.php?error=true&nodisk=true"); 
     return; 
    } 
}else { 
    header("Location: login.php?error=true&nowrite=true"); 
    return; 
} 

然後在login.php我有這個來捕獲錯誤代碼。

// If we have an error show error message 
if ( isset($_GET["error"]) && $_GET["error"] ) { 

    //If not enough disk space show disk space message 
    if(isset($_GET["nodisk"]) && $_GET["nodisk"]){ 
     alert("disk free problem"); 
    } 

    //If we don't have permission to session save path show session creation error 
    if(isset($_GET["nowrite"]) && $_GET["nowrite"]){ 
     alert("write permission error"); 
} 
1

您可能想要嘗試is_writable函數。

喜歡的東西:

<?php 
    $dirname = '/tmp'; 
    if (is_writable($dirname)) { 
     echo 'The folder is writable'; 
    } else { 
     echo 'The folder is not writable'; 
    } 
?> 

您可以用文件或文件夾使用它。

的更多信息:http://id1.php.net/is_writable

+0

這對我很有幫助。由於弗雷德裏克的回答,我在檢查用戶身份驗證之前就明白了只是檢查磁盤空間並寫權限。 – rccoros

+0

您可能想將它設置爲比以下有用的答案;) –