How can PHP developers ensure that non-existent pages return a 404 error instead of redirecting to the homepage?

To ensure that non-existent pages return a 404 error instead of redirecting to the homepage, PHP developers can use the header() function to set the HTTP response code to 404. This will inform the browser that the requested page was not found. Additionally, developers can customize the error page to display a user-friendly message to the visitors.

<?php
if (!file_exists($_SERVER['DOCUMENT_ROOT'] . $_SERVER['REQUEST_URI'])) {
    http_response_code(404);
    include('404-error-page.php'); // Include a custom error page
    exit();
}
?>