When to send HTTP status code?

2019-05-11 05:44发布

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!

6条回答
Melony?
2楼-- · 2019-05-11 06:33

You can't use 404 and Location: together. Location is valid only for some responses (201, and 3xx)

You can however send custom HTML page as body of your 404 response.

查看更多
淡お忘
3楼-- · 2019-05-11 06:34

From php.net:

There are two special-case header calls. The first is a header that starts with the string "HTTP/" (case is not significant), which will be used to figure out the HTTP status code to send. For example, if you have configured Apache to use a PHP script to handle requests for missing files (using the ErrorDocument directive), you may want to make sure that your script generates the proper status code.

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

http://us.php.net/manual/en/function.header.php

查看更多
Anthone
4楼-- · 2019-05-11 06:38

You should do something like this:

header("HTTP/1.0 404 Not Found");
include 'error.php';
die();
查看更多
淡お忘
5楼-- · 2019-05-11 06:41

A "redirect" and a "not found" are different concepts.

Which file could be found?
http://www.mydomain.com/error/notfound/
or
http://www.mydomain.com/not_exist.html

The "http://www.mydomain.com/not_exist.html" page should have a 404 header AND the "Page not Found" contents.

A quickfix could be:

header("HTTP/1.0 404 Not Found");
readfile('http://www.mydomain.com/error/notfound/');
exit;

But this requires 2 apache requests and is kind of nasty.

查看更多
爷的心禁止访问
6楼-- · 2019-05-11 06:42

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
查看更多
倾城 Initia
7楼-- · 2019-05-11 06:43

You should send a 404 HTTP status code. Browsers and crawlers understand this. You may also want to include a more friendly error page explaining what happened, including a form to search your site, Soundex links, etc.

查看更多
登录 后发表回答