PHP Error Handling Introduction
In this page:
Types of Errors in PHP
PHP distinguishes several error severities: notices flag minor issues like an undefined variable, warnings report bigger problems without halting execution, and fatal errors stop the script immediately -- knowing which is which shapes how urgently you need to react.
Example: Types of Errors in PHP
<?php
echo $undefinedVar ?? "notice: undefined variable";
echo "\n";
echo 10 / 2; // no error
?>
Login to try C/C++/Java/PHP code in the editor
Configuring Error Reporting Level
The error_reporting() function controls which of those severities actually get displayed or logged, letting you show everything during development while silencing minor notices in production.
Example: Configuring Error Reporting Level
<?php
error_reporting(E_ALL);
echo "All errors, warnings, and notices will now be shown";
?>
Login to try C/C++/Java/PHP code in the editor
Triggering Custom Errors
trigger_error() lets your own code raise a warning or notice on demand, which is useful for flagging suspicious application-level conditions (like a deprecated function call) the same way PHP flags its own issues.
Example: Triggering Custom Errors
<?php
function useOldFunction() {
trigger_error("This function is deprecated", E_USER_WARNING);
}
useOldFunction();
?>
Login to try C/C++/Java/PHP code in the editor
Custom Error Handlers
set_error_handler() lets you register a custom function that intercepts PHP's built-in errors, so you can log them, format them consistently, or hide raw error details from end users.
Example: Custom Error Handlers
<?php
set_error_handler(function ($errno, $errstr) {
echo "Custom handler caught: $errstr";
});
echo $undefinedVar;
?>
Login to try C/C++/Java/PHP code in the editor
Clean Error Recovery
restore_error_handler() reverts back to PHP's default error handling once your custom handler is no longer needed, which matters if you only want custom handling active for a specific block of code.
Example: Clean Error Recovery
<?php
set_error_handler(function ($errno, $errstr) {
echo "Custom: $errstr\n";
});
restore_error_handler();
echo "Back to PHP's default error handling";
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 5 topics to unlock
0/5 topics done
Complete these topics first: