Error Handling
5 min read Quiz at the end
PHP reports issues as warnings, notices, and fatal errors. Use error_reporting() to control what is shown. Set display_errors to Off in production and log errors to a file instead of exposing them to users.
Error Handling // Error levels
// E_ERROR — fatal, stops execution
// E_WARNING — non-fatal, execution continues
// E_NOTICE — informational
// E_ALL — all errors
// Set error reporting
error_reporting(E_ALL);
ini_set("display_errors", 0); // hide from users
ini_set("log_errors", 1); // log instead
ini_set("error_log", "/var/log/php_errors.log");
// Trigger errors
trigger_error("Custom warning", E_USER_WARNING);
// Custom error handler
set_error_handler(function($code, $msg, $file, $line) {
error_log("[$code] $msg in $file:$line");
return true; // don't execute PHP internal handler
});
// Suppress single expression (avoid in production)
$result = @file_get_contents("missing.txt");
Topic Quiz · 5 questions
Test your understanding before moving on
1. Which error level covers all errors?
A. E_ERROR
B. E_WARNING
C. E_ALL
D. E_DEBUG
💡 E_ALL includes all error levels, useful during development.
2. Which function sets a custom error handler?
A. register_error_handler()
B. set_error_handler()
C. error_set_handler()
D. define_error_handler()
💡 set_error_handler() registers a user-defined function to handle errors.
3. What does error_reporting(0) do?
A. Report all errors
B. Disable all error reporting
C. Report only fatal errors
D. Enable debug mode
💡 error_reporting(0) suppresses all error reporting.
4. Which ini setting logs errors to a file?
A. error_file
B. log_errors (with error_log path)
C. php_log
D. debug_log
💡 Set log_errors=1 and error_log=/path/to/file in php.ini to log errors.
5. Why should display_errors be off in production?
A. Performance
B. Security — stack traces expose sensitive info to attackers
C. Not required
D. Memory usage
💡 Displaying errors in production can expose file paths, DB credentials, and logic.
Submit answers