Codeigniter & PHP - forcing a 404?


In codeigniter, as you know, a page of the form: /class/function/ID, where class is the controller name, function is the method within the controller, and ID is the parameter to pass to that method.

The typical usage would be (for a book site for example) to pass the book id to the function which would then query the database for appropriate book. My problem is this: I was messing around and randomly (in the url string) typed in an ID that is not present in the database (with normal point and click browsing this would never happen) and I get database errors due to the residual queries I attempt to perform using a non-existent ID.

I have written code to check if there are any rows returned before attempting to use the ID, but if the ID is non-existent I would like the user to get a 404 error page rather than a blank page or something (since this seems like proper functionality). This would need to be a true 404 page (not simply loading a view that looks like a 404 page) so as not to screw with search engines. Okay - so my question is this: within normal program logic flow (as described above) how can I force a 404 error using codeigniter? Thanks.

Update: code igniter has a show_404('page') function but I don't think this will generate a true HTTP 404 error...

8/6/2009 3:01:30 AM

Accepted Answer

show_404() actually sends the proper headers for a search engine to register it as a 404 page (it sends 404 status).

Use a Firefox addon to check the headers received when calling show_404(). You will see it sends the proper HTTP Status Code.

Check the default application/errors/error_404.php. The first line is:

<?php header("HTTP/1.1 404 Not Found"); ?>

That line sets the HTTP Status as 404. It's all you need for the search engine to read your page as a 404 page.

8/6/2009 3:05:08 AM


to generate 404 headers.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow