views:

326

answers:

2

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

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

+2  A: 

You can stop the error message from displaying either by suppressing error messages globally (in config or runtime) with the display_errors setting, or case by case by prefixing the function call with an @-character. (E.g. @mkdir('...')).

You can then check with error_get_last when mkdir returns false.

For error logging global rules apply. You can log errors manually with error_log.

For further reading, see the manual section on Error handling.

Edit:

As suggested in the comments, a custom error handler is also a possible, arguably more robust (depending on your implementation) but certainly more elegant, solution.

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

set_error_handler('err_handler');

This way, the error message will not display, unless you explicitly echo it. Note, though, when using a custom error handler error_get_last will return NULL.

nikc
I should point out it's good practice as well as constructive to comment when downvoting. (Not to mention polite.)
nikc
I didn't downvote you, but maybe it's because someone saw the @-operator and considers it bad practise? (I do, myself, I'd suggest a custom error handler instead, with `set_error_handler`, but I think this answer is still *very* valid and helpful.)
pinkgothic
Indeed, a custom error handler would be a more elegant solution. But in cases as described I think the @-operator is an acceptable solution, since it looks to me as a one off situation.
nikc
+1  A: 

I would just like to have it write to a message to me in a custom log.

the solution is very easy. PHP already have everything for you:

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

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

If you don't want this error to be logged (as it may be not error but part of application logic), you can check folder existence first

if (!file_exists($folder)) mkdir($folder);
else {/*take some appropriate action*/}
Col. Shrapnel
You caught on to what I was trying to do. I can avoid the situation entirely by using file_exsists(). I used your answer to solve my problem. Thank You.
Doodle
I have to say that both answers where good and nikc's answers is definitely more technically correct especially about handling the error. I imagine Shrapnel knew that I was just screwing up and wouldn't need to handle any errors if I just did things right =)
Doodle