Php mkdir () exception handling

mkdir () is working correctly, this question is more about catching an error. Instead of printing this when the directory exists, I just would like it to write me a message in a special journal. How to create this exception.

Warning: mkdir () [function.mkdir]: File exists

+4
source share
3 answers

I would just like him to write me a message in a special journal.

The solution is very simple. PHP already has everything for you:

ini_set('display_errors',0); ini_set('log_errors',1); ini_set('error_log','/path/to/custom.log'); 

or the same settings in php.ini or .htaccess
I think it would be better than writing every possible error manually

If you do not want this error to be recorded (as it may not be an error, but part of the application logic), you can first check the existence of the folder

 if (!file_exists($folder)) mkdir($folder); else {/*take some appropriate action*/} 
+10
source

You can disable the display of error messages by suppressing error messages globally (in configuration or runtime) with the display_errors parameter, or in each case by prefixing the function call with @ -character. (For example, @mkdir('...') ).

Then you can check error_get_last when mkdir returns false .

The global rules apply to error logging. You can log errors manually using error_log .

See the Error Handling section of the manual for further reference.

Edit:

As pointed out in the comments, a custom error handler is also possible, possibly more reliable (depending on your implementation), but, of course, a more elegant solution.

 function err_handler($errno, $errstr) { // Ignore or log error here } set_error_handler('err_handler'); 

Thus, the error message will not be displayed unless you explicitly pronounce it. However, note that when using a custom error handler, error_get_last will return NULL .

+2
source

You can rewrite any system call function with a class like this:

file: system.php

 namespace abc; class System { const CAN_NOT_MAKE_DIRECTORY = 1; static public function makeDirectory($path) { $cmd = "mkdir " . $path; $output = \shell_exec($cmd . " 2>&1"); // system call if ($output != "") { throw new \Exception($output, System::CAN_NOT_MAKE_DIRECTORY); } return(\TRUE); } } 

Then you can call the method and catch the exception:

file: index.php

 namespace abc; require 'system.php'; try { System::makeDirectory($directoryName); } catch (\Exception $e) { throw new \Exception($e->getMessage(), System::CAN_NOT_MAKE_DIRECTORY); } 

Now you can handle all system errors normally with try {...} catch(...) {...} finally {...} .

+1
source

Source: https://habr.com/ru/post/1307515/


All Articles