📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials PHP for Beginners Error Handling

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?
💡 E_ALL includes all error levels, useful during development.
2. Which function sets a custom error handler?
💡 set_error_handler() registers a user-defined function to handle errors.
3. What does error_reporting(0) do?
💡 error_reporting(0) suppresses all error reporting.
4. Which ini setting logs errors to a file?
💡 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?
💡 Displaying errors in production can expose file paths, DB credentials, and logic.