Home > Article > Backend Development > How to Simulate a 404 Error and Display a Custom Error Page Using PHP?
In web development, handling errors is crucial for providing a seamless user experience. One common issue that developers face is creating custom error 404 pages, especially when using a .htaccess file for URL handling. This article addresses this specific scenario by explaining how to simulate an error 404 using PHP.
The provided code using header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found"); is not effectively triggering the 404 page configured in the .htaccess file. The question arises whether redirecting to the custom error 404 page is an incorrect approach.
To generate custom error 404 pages in PHP, it is recommended to use the http_response_code function introduced in PHP 5.4 and above:
<?php http_response_code(404); include('my_404.php'); // provide your own HTML for the error page die(); ?>
By employing the http_response_code function, you can effectively simulate an error 404 and display your custom error page when handling URLs that are not found in your internal endpoint script.
The above is the detailed content of How to Simulate a 404 Error and Display a Custom Error Page Using PHP?. For more information, please follow other related articles on the PHP Chinese website!