How to find a reason when mkdir fails from PHP?

前端 未结 3 1479
萌比男神i
萌比男神i 2020-12-01 18:05

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 scr

相关标签:
3条回答
  • 2020-12-01 18:47

    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);
    }
    
    0 讨论(0)
  • 2020-12-01 18:54

    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()
    
    0 讨论(0)
  • 2020-12-01 18:55

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

    if (!@mkdir($dir)) {
        $error = error_get_last();
        echo $error['message'];
    }
    
    0 讨论(0)
提交回复
热议问题