I wanted to be able to catch the error in session creation in PHP. My primary target is to be able to know which causes the problem. Is it because we don't have wrtie access to the folder where the session is written or because we don't have free disk space already.

So of course we will start with this.

session_start();

and from this post Check if session is set or not, and if not create one? I did try to add

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

 }
 else
 {
      // session has been started
 }

And to test this I have remove writing permissions for the group and others in /tmp/ by using this command

chmod 755 tmp/

But base on my test I still see that the session is started. And the funny thing is I can login but when I try to logout I can't.

Any insights on how to properly get the reason on session creation error would be greatly appreaciated. Thanks!

EDIT:

I have tried Frederik's suggestion and done this.

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

But I still see this

Session started. fa505cbf4b232773669008495fd08b9f

even if I have remove write permission to /tmp already. It seems that the try catch was not able to properly catch the problem.

有帮助吗?

解决方案 2

With Frederik's suggestion to check if the /tmp do have write permission I was able to decide to just check for write permission and disk space before checking for username and password. So I wrote this code

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;
}

and then in login.php I have this to catch the error code.

// 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");
}

其他提示

You might want to try the is_writable function.

Something like:

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

You can use it with files or folders.

More information: http://id1.php.net/is_writable

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top