Home > Backend Development > PHP Tutorial > How to Properly Display a Custom Error 404 Page in PHP?

How to Properly Display a Custom Error 404 Page in PHP?

Mary-Kate Olsen
Release: 2024-11-08 14:03:02
Original
259 people have browsed it

How to Properly Display a Custom Error 404 Page in PHP?

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

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:

  1. Set the HTTP response code to 404 using http_response_code(404);
  2. Include a custom 404 page HTML file using include('my_404.php');
  3. Terminate the script with die(); to prevent further execution.
<?php
http_response_code(404);
include('my_404.php');
die();
?>
Copy after login

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!

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