PHP Error Handling | PHP Tutorial - Learn with VOKS
Advance AI Bootstrap C C++ Computer Vision Content Writing CSS Cyber Security Data Analysis Deep Learning Email Marketing Excel Figma HTML Java Script Machine Learning MySQLi Node JS PHP Power Bi Python Python for AI Python for Analysis React React Native SEO SMM SQL
Back Next

PHP Error Handling

Learn this topic step-by-step with VOKS Tutorials.

Types of PHP Errors

Example of a Notice:

<?php
echo $undefined_variable; // Notice: Undefined variable
?>

Example of a Warning:

<?php
include('nonexistent_file.php'); // Warning: file not found
echo "Script continues...";
?>


Displaying Errors

During development, it’s helpful to display errors.

<?php
ini_set('display_errors', 1);  // Turn on error display
error_reporting(E_ALL);        // Show all errors and warnings
?>

Best practice:

  • Display errors on development servers only.
  • On production, turn off error display to prevent sensitive information leaks:
ini_set('display_errors', 0);


Custom Error Handling Using set_error_handler()

PHP allows you to define a custom function to handle errors:

<?php
// Custom error function
function myErrorHandler($errno, $errstr, $errfile, $errline) {
    echo "<b>Error:</b> [$errno] $errstr - in $errfile on line $errline<br>";
}

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

// Trigger an error
echo $undefined_variable; // Will call myErrorHandler
?>
  • $errno → Error number
  • $errstr → Error message
  • $errfile → File where error occurred
  • $errline → Line number of error


Handling Fatal Errors Using register_shutdown_function()

Fatal errors stop script execution. You can detect them before the script ends:

<?php
function shutdownHandler() {
    $error = error_get_last();
    if ($error) {
        echo "<b>Fatal Error:</b> {$error['message']} in {$error['file']} on line {$error['line']}";
    }
}

register_shutdown_function('shutdownHandler');

// Trigger a fatal error
nonexistentFunction(); // Fatal error: function doesn't exist
?>


Try-Catch Exception Handling

PHP supports exceptions, which is a modern way to handle errors. This is preferred for critical operations, such as database access.

<?php
try {
    $conn = new PDO("mysql:host=localhost;dbname=php_crud_demo", "root", "");
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // Trigger an exception
    $conn->query("SELECT * FROM nonexistent_table");
} catch (PDOException $e) {
    echo "Database Error: " . $e->getMessage();
} finally {
    echo "<br>Execution finished.";
}
?>

Notes:

  • try block → Code that might throw an error
  • catch block → Code to handle the error
  • finally block → Runs no matter what


Logging Errors to a File

Instead of displaying errors to the user, you can log them to a file:

<?php
ini_set("log_errors", 1);
ini_set("error_log", "php_errors.log");

// Trigger an error
echo $undefined_variable; 
?>
  • Check the php_errors.log file for errors.
  • Recommended for production environments.


Best Practices for Error Handling

  1. Use error reporting during development, but log errors in production.
  2. Avoid displaying sensitive error info to users.
  3. Use try-catch for critical operations, especially database queries.
  4. Always validate user input to prevent errors caused by unexpected data.
  5. Create a centralized error handling system for large projects.


What this demo does:

  • Shows a custom error using set_error_handler
  • Handles exceptions with try-catch
  • Triggers a notice and a warning
  • Lets learners see how different error types are handled


Practice Example: PHP Error Handling Demo

<?php
// Enable error reporting
ini_set('display_errors', 1);
error_reporting(E_ALL);

// Custom error handler
function myErrorHandler($errno, $errstr, $errfile, $errline) {
    echo "<b>Error:</b> [$errno] $errstr - in $errfile on line $errline<br>";
}
set_error_handler("myErrorHandler");

// Try-Catch Exception Handling
try {
    $num = 10;
    $den = 0;
    if ($den == 0) {
        throw new Exception("Division by zero not allowed!");
    }
    echo $num / $den;
} catch (Exception $e) {
    echo "Caught Exception: " . $e->getMessage();
}

// Trigger a notice
echo $undefined_variable;

// Trigger a warning
include('nonexistent_file.php');
?>
QUICK KNOWLEDGE CHECK

Test Your Understanding

Answer 5 questions generated from this lesson. Your result is calculated instantly and is not saved.

0 / 5 answered
All Courses
Advance AI Bootstrap C C++ Computer Vision Content Writing CSS Cyber Security Data Analysis Deep Learning Email Marketing Excel Figma HTML Java Script Machine Learning MySQLi Node JS PHP Power Bi Python Python for AI Python for Analysis React React Native SEO SMM SQL
Course contents
PHP
01 Introduction 02 PHP Configuration 03 PHP CRUD (Create, Read, Update, Delete) 04 PHP Error Handling 05 PHP Form Submission 06 Login System 07 PHP Comments