Skip to content
PHP Logo

How can PHP be effectively used to send email notifications with specific page information when a 404 error occurs?

When a 404 error occurs on a website, it can be helpful to send email notifications with specific information about the page that triggered the error. This can help website administrators quickly identify and address any broken links or missing pages. To achieve this, you can use PHP to capture the relevant error information and send an email notification using the `mail()` function.

php
<?php
// Check if a 404 error occurred
if (http_response_code() == 404) {
    $error_message = "404 Error: Page Not Found\n";
    $error_message .= "Requested URL: " . $_SERVER['REQUEST_URI'] . "\n";
    $error_message .= "Referring URL: " . $_SERVER['HTTP_REFERER'] . "\n";
    
    // Send email notification
    $to = "admin@example.com";
    $subject = "404 Error Notification";
    $headers = "From: webmaster@example.com";
    
    mail($to, $subject, $error_message, $headers);
}
?>