PHP set_error_handler
can catch various type of php errors in a specific portion of the code. To restore the previous error hander one can call restore_error_handler
function. Here is a sample code snippet and its outcome.
<?php function my_error_handler ($errno, $errstr, $errfile, $errline) { echo "errstr=$errstr"; // return true to bypass standard php error handler return true; } set_error_handler('my_error_handler', E_ALL | E_STRICT); // this will cause warning due to bad regex $ret = preg_match("abc", "abcdef"); restore_error_handler(); ?>
errstr=preg_match(): Delimiter must not be alphanumeric or backslash
Env: PHP 7.4.33 (Linux)
Few points to note
- Returning true from error handler will bypass php standard error handler.
- restore_error_handler will restore previous hander. In our case default php error handler.
- It is pretty useful in case you are executing code obtained from thord party.