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