HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

PHP Errors

Error handling is the process of catching errors raised by your program and then taking appropriate action. If you don't handle errors, your website might look broken or expose sensitive server information to users.


1. Types of Errors

PHP has several levels of errors. Understanding them helps you debug faster.

Error Type Description
E_ERRORFatal Error. Script execution stops immediately (e.g., calling a non-existent function).
E_WARNINGNon-fatal error. Script continues execution (e.g., including a missing file).
E_NOTICEMinor issue. Script continues (e.g., using an undefined variable).

2. Simple Error Handling: die()

The die() function prints a message and exits the current script. It is often used when a critical resource (like a database or file) is missing.

<?php
    if(!file_exists("welcome.txt")) {
        die("File not found! Stopping script.");
    } else {
        $file = fopen("welcome.txt", "r");
    }
?>

3. Custom Error Handlers

You can create a custom function to handle errors your way (e.g., logging them to a file or showing a pretty alert).

<?php
    // Error handler function
    function myErrorHandler($errno, $errstr) {
        echo "<b>Error:</b> [$errno] $errstr<br>";
        echo "Webmaster has been notified.";
        die();
    }

    // Set error handler
    set_error_handler("myErrorHandler");

    // Trigger error
    echo($test); // Undefined variable triggers the handler
?>
Production Tip: In a live environment, you should turn off error display to users using ini_set('display_errors', 0); and log errors to a private file instead.
Fatal Limits: Custom error handlers (set_error_handler) cannot catch E_ERROR (Fatal Errors) because the script stops before the handler can run. To catch these, you need Try/Catch blocks.
Pro Tip: Use trigger_error() to manually fire an error when user input doesn't meet your business logic requirements.

Key Takeaways

  • Notices and Warnings don't stop the script.
  • Fatal Errors stop execution immediately.
  • die() and exit() are identical for stopping scripts.
  • Use set_error_handler() for global custom logic.
  • Never show raw PHP errors to end-users in production.