views:

238

answers:

4

My .htaccess redirects all requests to /word_here to /page.php?name=word_here. The PHP script then checks if the requested page is in its array of pages.

If not, how can I simulate an error 404? I tried this, but it didn't work:

header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");

Am I right in thinking that it's wrong to redirect to my error 404 page?

+1  A: 

Try this:

<?php
header("HTTP/1.0 404 Not Found");
?>
Ates Goral
So you think switching to HTTP 1.0 will solve that issue?
Gumbo
Well a 404 is a 404 both in HTTP 1.0 and 1.1. 1.0 is a safe bet. Cool joke BTW :) +1
Ates Goral
+3  A: 

What you're doing will work, and the browser will receive a 404 code. What it won't do is display the "not found" page that you might be expecting, e.g.:

Not Found

The requested URL /test.php was not found on this server.

That's because the web server doesn't send that page when PHP returns a 404 code (at least Apache doesn't). PHP is responsible for sending all its own output. So if you want a similar page, you'll have to send the HTML yourself, e.g.:

<?php
header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
include("notFound.php");
?>

You could configure Apache to use the same page for its own 404 messages, by putting this in httpd.conf:

ErrorDocument 404 /notFound.php
JW
Thanks. I'd assumed it used my 404 page.
Eric
A: 

Did you remember to die() after sending the header? The 404 header doesn't automatically stop processing, so it may appear not to have done anything if there is further processing happening.

It's not good to REDIRECT to your 404 page, but you can INCLUDE the content from it with no problem. That way, you have a page that properly sends a 404 status from the correct URL, but it also has your "what are you looking for?" page for the human reader.

Eli
A: 

What about something like this?

header ("HTTP/1.1 404 Not Found");
echo file_get_contents('../path_to_your_error_page');

What happens here is you send the correct header and then echo out a custom 404 page.

Scott