Home > Article > Backend Development > How do I set up custom 404 error pages in PHP?
Setting Up Error 404 Pages in PHP
When a requested page is not found within the available pages, it's essential to display an appropriate error 404 page. PHP provides several methods to achieve this.
Utilizing http_response_code for Error 404
In PHP 5.4 and later, the recommended approach is to use the http_response_code function. This method explicitly sets the HTTP response code for the current request:
<?php http_response_code(404); include('my_404.php'); // Custom HTML for the error page die(); ?>
Using header() to Simulate Error 404
An alternative method is to employ the header() function. However, it's important to note that this approach simulates an error 404 rather than actually producing one:
header($_SERVER["SERVER_PROTOCOL"] . " 404 Not Found");
Configuring ErrorDocument in .htaccess
To configure your custom error 404 page via .htaccess, you can add the following directive:
ErrorDocument 404 /404.php
This will direct requests for non-existent pages to the specified 404.php file.
Redirecting to Error 404 Page
Redirect to an error 404 page is discouraged as it can harm SEO performance. Search engines like Google may struggle to crawl your website if you redirect to internal error pages.
The above is the detailed content of How do I set up custom 404 error pages in PHP?. For more information, please follow other related articles on the PHP Chinese website!