How to find a reason when mkdir fails from PHP?

39,655

Solution 1

You can suppress the warning and make use of error_get_last():

if (!@mkdir($dir)) {
    $error = error_get_last();
    echo $error['message'];
}

Solution 2

You could use exceptions:

Setup some code like so:

function exception_error_handler($errno, $errstr, $errfile, $errline ) {
    throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}
set_error_handler("exception_error_handler");

And then just do:

try {
   mkdir('/somedir');
} catch(ErrorException $ex) {
   echo "Error: " . $ex->getMessage();
}

That should do what you want.

If you want to preserve the php error handler, then after that try catch block, just call:

restore_error_handler()

Solution 3

I use something like the following:

if(! @mkdir('$fileLocation', 0777, $recursive = true)){
    $mkdirErrorArray = error_get_last();
    throw new Exception('cant create directory ' .$mkdirErrorArray['message'], 1);
}
Share:
39,655
Milan Babuškov
Author by

Milan Babuškov

Software developer, owner of a small ISV company, project manager of the open source FlameRobin project. Specialized in Linux, C++, PHP and Relational databases. You can read my software related blog at http://www.BackwardCompatible.net You can also buy my shareware software at http://www.GuacoSoft.com

Updated on July 14, 2022

Comments

  • Milan Babuškov
    Milan Babuškov almost 2 years

    PHP's mkdir function only returns true and false. Problem is when it returns false.

    If I'm running with error reporting enabled, I see the error message on the screen. I can also see the error message in the Apache log. But I'd like to grab the text of the message and do something else with it (ex. send to myself via IM). How do I get the error text?

    Update: Following Ayman's idea, I came to this:

    function error_handler($errno, $errstr) {
        global $last_error;
        $last_error = $errstr;
    }
    
    set_error_handler('error_handler');
    if (!mkdir('/somedir'))
        echo "MKDIR failed, reason: $last_error\n";
    restore_error_handler();
    

    However, I don't like it because it uses global variable. Any idea for a cleaner solution?