How do I set up custom 404 error pages in PHP?

Barbara Streisand
Release: 2024-11-08 15:51:02
Original
826 people have browsed it

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();
?>
Copy after login

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");
Copy after login

Configuring ErrorDocument in .htaccess

To configure your custom error 404 page via .htaccess, you can add the following directive:

ErrorDocument 404 /404.php
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template