Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to send HTTP status code?

Currently in my PHP scripts, I redirect the user to a custom 404 not found error page when he/she tries to access content that doesn't exist or doesn't belong to that user. Like so:

header('Location: http://www.mydomain.com/error/notfound/');
exit;

I realize the above header() call sends a 302 redirect status code by default.

What I don't understand, however, is when I should send the 404 not found status code. Before I redirect the user? Or when I display the /error/notfound/ page?

Thanks for your help!

like image 275
Justin Stayton Avatar asked Nov 28 '22 20:11

Justin Stayton


2 Answers

You should do something like this:

header("HTTP/1.0 404 Not Found");
include 'error.php';
die();
like image 154
Pim Jager Avatar answered Dec 08 '22 00:12

Pim Jager


You don't execute 404 errors as a redirect at all.

What you really want to do is send the 404 status header, and then replace the current output with the body of a 404 page.

There are various ways to do this and it depends quite a bit on how your site is structured. MVC applications typically hand this with a forward. I've seen other systems that throw an Exception and then the registered exception handler takes care of displaying the 404 page.

At any rate, the rough steps are

  1. Determine content is invalid
  2. Break out of current execution
  3. Clear any output, should there be any.
  4. Send the 404 status header
  5. Send the content of the 404 page
like image 22
Peter Bailey Avatar answered Dec 07 '22 23:12

Peter Bailey