Alex Rivera | Logout

Why won't my PHP app send a 404 error?

Asked 2009-01-12T22:26:20.180
141
if (strstr($_SERVER['REQUEST_URI'],'index.php')) {
    header('HTTP/1.0 404 Not Found');
}

Why wont this work? I get a blank page.

Edit
Report

3 Answers

307

Your code is technically correct. If you looked at the headers of that blank page, you'd see a 404 header, and other computers/programs would be able to correctly identify the response as file not found.

Of course, your users are still SOL. Normally, 404s are handled by the web server.

  • User: Hey, do you have anything for me at this URI webserver?
  • Webserver: No, I don't, 404! Here's a page to display for 404s.

The problem is, once the web server starts processing the PHP page, it's already passed the point where it would handle a 404

  • User: Hey, do you have anything for me at this URI webserver?
  • Webserver: Yes, I do, it's a PHP page. It'll tell you what the response code is
  • PHP: Hey, OMG 404!!!!!!!
  • Webserver: Well crap, the 404 page people have already gone home, so I'll just send along whatever PHP gave me

In addition to providing a 404 header, PHP is now responsible for outputting the actual 404 page.

answered 2009-01-13T01:39:44.080
2

A little bit shorter version. Suppress odd echo.

if (strstr($_SERVER['REQUEST_URI'],'index.php')){
  header('HTTP/1.0 404 Not Found');
  exit("<h1>404 Not Found</h1>\nThe page that you have requested could not be found.");
}
answered 2010-10-10T05:55:12.070
1

If you want the server’s default error page to be displayed, you have to handle this in the server.

answered 2009-01-12T23:37:58.447

Your Answer