Customize Consent Preferences

We use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.

The cookies that are categorized as "Necessary" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... 

Always Active

Necessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.

No cookies to display.

Functional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.

No cookies to display.

Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.

No cookies to display.

Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.

No cookies to display.

Advertisement cookies are used to provide visitors with customized advertisements based on the pages you visited previously and to analyze the effectiveness of the ad campaigns.

No cookies to display.

Notify by email of 500 errors or exceptions with PHP

Tiempo de lectura: 2 minutos

When developing web applications in PHP, it is essential to handle errors effectively to ensure a smooth user experience and to promptly notify system administrators of any issues. In this tutorial, we will learn how to implement a basic exception handling system that will automatically send an email to the administrator when a 500 error occurs in our application.

Step 1: Configuration of the handler.php File

Firstly, we will create a file named handler.php that will contain our exception handling and email sending functions. This file can be included in all scripts of our application.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<?php
// Set the email address to which the message will be sent
$recipient = 'contact@email.com';
// Function to send an email
function sendEmail($message, $recipient) {
$subject = 'Error 500 on the website';
$headers = 'From: webmaster@example.com' . "\r\n" .
'Reply-To: webmaster@example.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
// Use PHP's mail() function to send the email
mail($recipient, $subject, $message, $headers);
}
// Function to handle exceptions
function handleException($exception) {
// Get information about the exception
$message = 'An error has occurred on the website.' . "\n\n";
$message .= 'Error message: ' . $exception->getMessage() . "\n";
$message .= 'File: ' . $exception->getFile() . "\n";
$message .= 'Line: ' . $exception->getLine() . "\n";
// Send an email with the error information
sendEmail($message, $GLOBALS['recipient']);
// You can log the error somewhere else, like a log file
// Show a generic message to the user (optional)
echo 'An error has occurred. The administrator has been notified.';
// You can redirect the user to a custom error page if you wish
// header('Location: error.php');
}
// Set the custom exception handling function
set_exception_handler('handleException');
// Generate a 500 error (for example, trying to access an undefined variable)
echo $undefinedVariable;
?>
<?php // Set the email address to which the message will be sent $recipient = 'contact@email.com'; // Function to send an email function sendEmail($message, $recipient) { $subject = 'Error 500 on the website'; $headers = 'From: webmaster@example.com' . "\r\n" . 'Reply-To: webmaster@example.com' . "\r\n" . 'X-Mailer: PHP/' . phpversion(); // Use PHP's mail() function to send the email mail($recipient, $subject, $message, $headers); } // Function to handle exceptions function handleException($exception) { // Get information about the exception $message = 'An error has occurred on the website.' . "\n\n"; $message .= 'Error message: ' . $exception->getMessage() . "\n"; $message .= 'File: ' . $exception->getFile() . "\n"; $message .= 'Line: ' . $exception->getLine() . "\n"; // Send an email with the error information sendEmail($message, $GLOBALS['recipient']); // You can log the error somewhere else, like a log file // Show a generic message to the user (optional) echo 'An error has occurred. The administrator has been notified.'; // You can redirect the user to a custom error page if you wish // header('Location: error.php'); } // Set the custom exception handling function set_exception_handler('handleException'); // Generate a 500 error (for example, trying to access an undefined variable) echo $undefinedVariable; ?>
<?php

// Set the email address to which the message will be sent
$recipient = 'contact@email.com';

// Function to send an email
function sendEmail($message, $recipient) {
    $subject = 'Error 500 on the website';
    $headers = 'From: webmaster@example.com' . "\r\n" .
                 'Reply-To: webmaster@example.com' . "\r\n" .
                 'X-Mailer: PHP/' . phpversion();

    // Use PHP's mail() function to send the email
    mail($recipient, $subject, $message, $headers);
}

// Function to handle exceptions
function handleException($exception) {
    // Get information about the exception
    $message = 'An error has occurred on the website.' . "\n\n";
    $message .= 'Error message: ' . $exception->getMessage() . "\n";
    $message .= 'File: ' . $exception->getFile() . "\n";
    $message .= 'Line: ' . $exception->getLine() . "\n";
    
    // Send an email with the error information
    sendEmail($message, $GLOBALS['recipient']);

    // You can log the error somewhere else, like a log file

    // Show a generic message to the user (optional)
    echo 'An error has occurred. The administrator has been notified.';

    // You can redirect the user to a custom error page if you wish
    // header('Location: error.php');
}

// Set the custom exception handling function
set_exception_handler('handleException');

// Generate a 500 error (for example, trying to access an undefined variable)
echo $undefinedVariable;

?>

Step 2: Inclusion of the handler.php File in Your PHP Scripts

Now, in each of your PHP scripts, include the handler.php file at the beginning to enable exception handling and email sending.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// index.php
<?php
// Include the handler.php file
include 'handler.php';
// Rest of the code for your main script
// ...
// Generate a 500 error (for example, trying to access an undefined variable)
echo $undefinedVariable;
?>
// index.php <?php // Include the handler.php file include 'handler.php'; // Rest of the code for your main script // ... // Generate a 500 error (for example, trying to access an undefined variable) echo $undefinedVariable; ?>
// index.php

<?php

// Include the handler.php file
include 'handler.php';

// Rest of the code for your main script
// ...

// Generate a 500 error (for example, trying to access an undefined variable)
echo $undefinedVariable;

?>
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// another_script.php
<?php
// Include the handler.php file
include 'handler.php';
// Rest of the code for your other script
// ...
// Generate a 500 error (for example, trying to access an undefined variable)
echo $anotherUndefinedVariable;
?>
// another_script.php <?php // Include the handler.php file include 'handler.php'; // Rest of the code for your other script // ... // Generate a 500 error (for example, trying to access an undefined variable) echo $anotherUndefinedVariable; ?>
// another_script.php

<?php

// Include the handler.php file
include 'handler.php';

// Rest of the code for your other script
// ...

// Generate a 500 error (for example, trying to access an undefined variable)
echo $anotherUndefinedVariable;

?>

If instead of sending by email, we want to display the error in the console:

<

pre class=”EnlighterJSRAW” data-enlighter-language=”generic” data-enlighter-theme=”” data-enlighter-highlight=”” data-enlighter-linenumbers=”” data-enlighter-lineoffset=”” data-enlighter-title=”” data-enlighter-group”>
$currentDate = date(‘Y-m-d H:i:s’);
$errorString = $currentDate . $message;
// Output log to console (docker)
file_put_contents(‘php://stdout’, $errorString . “\n”);

Conclusion:

With these simple steps, you have implemented a basic but effective PHP exception handling system that will automatically send emails to the administrator when a 500 error occurs in your application. Customize the functions according to your specific needs, and keep in mind that this is just a starting point; you can expand and enhance this functionality based on your project requirements.

You are now better equipped to maintain and manage your PHP application more effectively!
“`

0

Leave a Comment