Print Errors and Warnings in PHP

Error handling is an essential part of PHP development. In this tutorial, we will learn how to print errors and warnings in PHP to help you debug your applications effectively.

Step 1: Displaying Errors in PHP

By default, PHP may not display errors and warnings. To enable error reporting, you can use the following configuration settings at the beginning of your script:


<?php
// Enable error reporting
error_reporting(E_ALL); // Report all PHP errors
ini_set('display_errors', 1); // Display errors on the screen
?>
    

Step 2: Creating a Sample Error

Let’s create a simple example that will generate an error. The following code attempts to divide a number by zero:


<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

// This will generate a warning
$result = 10 / 0; // Division by zero
?>
    

Step 3: Custom Error Handling

You can also create a custom error handler using the set_error_handler() function. This allows you to define how errors are handled and displayed:


<?php
function customError($errno, $errstr) {
    echo "Error: [$errno] $errstr
"; die(); // Stop script execution } set_error_handler("customError"); // This will trigger the custom error handler $result = 10 / 0; // Division by zero ?>

Step 4: Logging Errors

Instead of displaying errors on the screen, you might want to log them to a file for later review. You can do this by setting the log_errors directive and specifying a log file:


<?php
ini_set('log_errors', 1);
ini_set('error_log', 'error_log.txt'); // Path to your log file

// This will be logged to the error_log.txt file
$result = 10 / 0; // Division by zero
?>
    

Final Thoughts

In this tutorial, you learned how to print errors and warnings in PHP using error reporting settings. You also explored custom error handling and logging errors to a file. Proper error handling is crucial for debugging and maintaining your PHP applications, so make sure to implement these techniques in your projects!

Leave a Comment