I am using unlink
on my PHP page. In some situations, Permission may be denied for deleting the directory. Instead of having
Warning: unlink(stuff/New folder) [function.unlink]: Permission denied in ... on line 30
show up on the rendered page, is there a way for me to do a "warning_get_last" that will capture the last given warning, so I can output it nicely? Or does error_get_last
include these?
I know I can suppress the warnings with @unlink
and that I can also check to see if unlink
returns false, but I would like to know the error message that goes along with it if it does fail.
Use error_reporting(0)
to not show the warning or any errors in the rendered page. It will still show up in your server error logs and you can still use error_get_last()
to get the last error.
You can test it out with this:
error_reporting(0);
unlink('some file that does not exist'); // generates a warning
print_r(error_get_last());
EDITED: Please note that error_reporting(0)
will affect subsequent code, so you'll want to set it back to the level you want after you're through the code where you want to suppress the error display.
You write set your own error handler, enable it just before the call, and revert back to normal afterwards.
Use set-error-handler to turn on the error handler, save to a global variable (that's the simplest - perhaps not most "correct") and show if there was an error. Or user error_get_last() (as suggeted by Trott).
function myErrorHandler($errno, $errstr, $errfile, $errline) {
global $lastErrorString;
$lastErrorString = $errstr;
return false;
}
// Calling function:
global $lastErrorString;
$lastErrorString=false;
$old_error_handler = set_error_handler("myErrorHandler");
unlink($file);
restore_error_handler();
if ($lastErrorString !== false) {
echo 'Went wrong: ' . $lastErrorString;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With