Home  >  Article  >  Backend Development  >  Why Doesn't My PHP Code Produce a 404 Error?

Why Doesn't My PHP Code Produce a 404 Error?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-11 06:25:02210browse

Why Doesn't My PHP Code Produce a 404 Error?

Solving the 404 Error Quandary in PHP Applications

In PHP development, it's sometimes necessary to return a 404 error to indicate a resource cannot be found. However, you may encounter a situation where a code like the following doesn't produce the intended 404 error.

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

Instead of displaying a 404 error, you may get a blank page. The issue lies in how web servers and PHP interact in handling 404 responses.

As explained in the provided answer:

  • Web servers typically handle 404 errors themselves, displaying a designated 404 page.
  • PHP, however, overrides this process by receiving the request and sending a 404 header.

This causes the web server to bypass its own 404 handling mechanism. As a result, instead of the intended 404 page, the web server sends whatever PHP produces, which is an empty page in this case.

To resolve this issue, PHP should send the 404 header before the web server starts processing PHP. This ensures the web server can properly handle the response and display the appropriate 404 page.

The corrected code:

header('HTTP/1.0 404 Not Found');
exit(); // To prevent any further PHP processing

The above is the detailed content of Why Doesn't My PHP Code Produce a 404 Error?. 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