Simulating Error 404 Page in PHP
When facing requests for unavailable pages, it becomes essential to create an error 404 page to indicate the requested resource is not found. One may attempt to simulate this error using PHP's header function, as seen below:
header($_SERVER["SERVER_PROTOCOL"] . " 404 Not Found");
However, such an approach redirects users to the error 404 page instead of displaying it, contradicting the intended behavior.
Using http_response_code for Modern PHP Versions
For PHP versions 5.4 and higher, the recommended method for generating 404 pages is to utilize the http_response_code function. The updated approach involves the following steps:
<?php http_response_code(404); include('my_404.php'); die(); ?>
This approach effectively displays the custom error 404 page rather than redirecting users, resolving the issue of displaying the appropriate error message for non-existent pages.
The above is the detailed content of How to Properly Display a Custom Error 404 Page in PHP?. For more information, please follow other related articles on the PHP Chinese website!