Home  >  Article  >  Backend Development  >  Why Does My PHP Code Fail to Display a 404 Error Page?

Why Does My PHP Code Fail to Display a 404 Error Page?

Susan Sarandon
Susan SarandonOriginal
2024-11-11 03:27:03540browse

Why Does My PHP Code Fail to Display a 404 Error Page?

HTTP 404 Error Handling in PHP

Question: Why does the following PHP code fail to generate a 404 error page?

if (strstr($_SERVER['REQUEST_URI'],'index.php')) {
    header('HTTP/1.0 404 Not Found');
}

Answer: The code technically sends a 404 header, but the user receives a blank page because:

  • Traditional 404 Handling: Web servers typically handle 404s by redirecting to a custom 404 page.
  • PHP Overriding: Once PHP processing begins, the server can no longer handle 404s. The PHP code must generate and display the 404 page itself.

In this case, the PHP code only sends the 404 header but does not provide the actual 404 page content. To fix this, you need to output the 404 page as well. For example:

if (strstr($_SERVER['REQUEST_URI'],'index.php')) {
    header('HTTP/1.0 404 Not Found');
    echo "<p>Page not found</p>";
}

The above is the detailed content of Why Does My PHP Code Fail to Display a 404 Error Page?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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