Home » Php » PHP – error_get_last method for warnings?

PHP – error_get_last method for warnings?

Posted by: admin July 12, 2020 Leave a comment

Questions:

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.

How to&Answers:

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());

Answer:

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;
}

Answer:

I fail to see why the following is any worse than the 2 other proposals; in fact I’d say it’s better because it’s shorter than Robbie’s answer and doesn’t have a global effect unlike Trott’s answer:

$ok = @unlink(...);
if ($ok === FALSE)
    throw new Exception(error_get_last()['message']);

Output when run:

PHP Fatal error:  Uncaught exception 'Exception' with message 'unlink(foobar.txt): No such file or directory' in /Users/erik/code/test.php:5
Stack trace:
#0 {main}
  thrown in /Users/erik/code/test.php on line 5