Skip to content

PHP By Exalogics

A Simple Easy Site to Learn, Understand and create php

Menu
  • Home
  • Welcome to php by Exalogics
    • Introduction to PHP
    • How to Install PHP on Windows
    • PHP Variables
    • PHP Constants
    • PHP Switch Statement
    • PHP Data Types
    • PHP Operators
    • PHP If Else Statements
    • PHP E-Commerce Development
    • Your First PHP Script
    • PHP Error Handling
    • PHP Frameworks Guide
    • PHP MySQL Database Development
    • PHP Security Best Practices
    • PHP CMS Development
    • PHP Hosting Guide
  • PHP API Development
Menu

How to Handle Errors in PHP

Posted on August 20, 2026






How to Handle Errors in PHP – Complete Guide for Developers



How to Handle Errors in PHP

When building robust PHP applications, proper error handling is essential. It not only helps developers debug issues faster but also prevents sensitive information from leaking to end users. This guide covers everything you need to know—from basic error reporting settings to advanced custom error handlers and exception management.

1. Understanding PHP Error Types

PHP categorizes errors into several levels. Knowing each type helps you decide how to respond.

1.1 Notices

Minor issues that don’t stop script execution, such as accessing an undefined variable.

1.2 Warnings

More serious problems, like including a missing file, but the script continues.

1.3 Fatal Errors

Critical errors that halt script execution, e.g., calling an undefined function.

1.4 Parse Errors

Syntax errors detected during compilation. The script never runs.

2. Configuring Error Reporting

Set the appropriate error reporting level for each environment (development, staging, production).

// Development (show all errors)
ini_set('display_errors', 1);
error_reporting(E_ALL);

// Production (log only, hide from users)
ini_set('display_errors', 0);
error_reporting(E_ALL & ~E_DEPRECATED & ~E_STRICT);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/logs/php-errors.log');

3. Using try / catch with Exceptions

Since PHP 5, the Exception class provides a modern way to handle errors.

try {
    // Code that may throw an exception
    $pdo = new PDO($dsn, $user, $pass);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    // ... other DB operations
} catch (PDOException $e) {
    // Log the error and show a generic message to the user
    error_log($e->getMessage());
    echo 'A database error occurred. Please try again later.';
}

4. Creating a Custom Error Handler

For full control, register a custom handler with set_error_handler(). This allows you to convert traditional PHP errors into Exceptions or log them in a structured format.

function myErrorHandler($severity, $message, $file, $line) {
    // Convert error to exception if it's not suppressed with @
    if (!(error_reporting() & $severity)) {
        return;
    }

    // Build a detailed error message
    $logMessage = sprintf(
        "[%s] %s in %s on line %d",
        date('Y-m-d H:i:s'),
        $message,
        $file,
        $line
    );

    // Log to file
    error_log($logMessage, 3, __DIR__ . '/logs/custom-errors.log');

    // Optionally throw an exception for critical errors
    if ($severity & (E_ERROR | E_CORE_ERROR | E_COMPILE_ERROR | E_USER_ERROR)) {
        throw new ErrorException($message, 0, $severity, $file, $line);
    }

    // Return true to bypass PHP's internal handler
    return true;
}

// Register the handler
set_error_handler('myErrorHandler');

5. Shutdown Functions for Fatal Errors

Fatal errors cannot be caught by set_error_handler(). Use register_shutdown_function() to capture them.

register_shutdown_function(function () {
    $error = error_get_last();
    if ($error && in_array($error['type'], [E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR, E_PARSE])) {
        $msg = sprintf(
            "Shutdown error: %s in %s on line %d",
            $error['message'],
            $error['file'],
            $error['line']
        );
        error_log($msg, 3, __DIR__ . '/logs/shutdown-errors.log');

        // Show a generic response to the user
        if (!headers_sent()) {
            http_response_code(500);
            echo 'An unexpected error occurred. Please contact support.';
        }
    }
});

6. Best Practices for Production

  • Never display raw errors to users. Use generic messages and log details securely.
  • Centralize logging. Use a library like Monolog to send logs to files, syslog, or external services.
  • Separate environments. Keep distinct php.ini or configuration files for development vs. production.
  • Monitor logs. Set up alerts (e.g., via Slack or email) for critical errors.
  • Test error handling. Write unit tests that trigger exceptions and verify your custom handlers work as expected.

7. Quick Checklist

  1. Set display_errors to 0 in production.
  2. Enable log_errors and define a secure log path.
  3. Use error_reporting(E_ALL) during development.
  4. Implement a global set_error_handler() to centralize error processing.
  5. Wrap risky code in try / catch blocks.
  6. Register a shutdown function for fatal errors.
  7. Regularly review and rotate log files.

Conclusion

Effective error handling in PHP is a blend of proper configuration, strategic use of exceptions, and custom logging. By following the steps outlined above, you’ll create applications that are easier to debug, more secure, and resilient in production environments.

Start implementing these practices today, and watch your PHP projects become more stable and professional.


Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recent Posts

  • Pakistan Tour Sri Lanka 2026: A Subcontinent Showdown
  • Pakistan Tour New Zealand 2025: Exploring the Kiwi Conditions
  • Pakistan Tour South Africa 2025: A Test of Grit and Skill
  • Pakistan Tour England: A Classic Rivalry Renewed
  • How to Create and Use Arrays in PHP

Recent Comments

  1. What are Magic Methods in PHP? (__construct, __destruct, __get, etc.) - 93 Travellers Pakistan on What are Magic Methods in PHP? (__construct, __destruct, __get, etc.)
  2. How to Use Traits in PHP - 93 Travellers Pakistan on How to Use Traits in PHP
  3. What is Polymorphism in PHP? - 93 Travellers Pakistan on What is Polymorphism in PHP?
  4. What is Inheritance in PHP? - 93 Travellers Pakistan on What is Inheritance in PHP?
  5. What is Abstraction in PHP? - 93 Travellers Pakistan on What is Abstraction in PHP?

Archives

  • October 2026
  • September 2026
  • August 2026
  • July 2026

Categories

  • PHP Basics
  • Uncategorized
©2026 PHP By Exalogics | Design: Newspaperly WordPress Theme
imunify-bot-check