简体   繁体   English

在PHP中设置HTTP响应代码(在Apache下)

[英]Setting a HTTP response code in PHP (under Apache)

Given the following two methods for setting a HTTP response code in PHP (specifically, under Apache): 给出以下两种在PHP中设置HTTP响应代码的方法(特别是在Apache下):

Method 1: 方法1:

http_response_code(404);

Method 2: 方法2:

header("HTTP/1.0 404 Not Found");

My questions are: 我的问题是:

  1. Aside from the fact that http_response_code is only available in PHP 5.4 or greater, what are the differences between the two approaches and why/when to use one over the other? 除了http_response_code仅在PHP 5.4或更高版本中可用之外,这两种方法之间有什么区别以及为什么/何时使用另一种方法?
  2. Where does the Reason Phrase come from when using the first example? 使用第一个例子时, 原因词组来自何处? (I've checked and a Reason Phrase is generated from somewhere) (我检查, 从什么地方产生原因短语)

Since I'm being downvoted into oblivion for no apparent reason, I've managed to answer this myself by scouring through the PHP source code. 由于我没有明显的理由被遗忘,我已经设法通过浏览PHP源代码来回答这个问题。 Hopefully this serves as a reference for anyone else trying to work this out. 希望这可以作为其他任何试图解决这个问题的人的参考。

The two methods are essentially functionally equivalent. 这两种方法在功能上基本相同。 http_response_code is basically a shorthand way of writing a http status header, with the added bonus that PHP will work out a suitable Reason Phrase to provide by matching your response code to one of the values in an enumeration it maintains within php-src/main/http_status_codes.h . http_response_code基本上是编写http状态标头的简便方法,还有一个额外的好处,PHP将通过将您的响应代码与它在php-src / main /中维护的枚举中的某个值匹配来提供合适的Reason Phrase。 http_status_codes.h

Note that this means your response code must match a response code that PHP knows about. 请注意,这意味着您的响应代码必须与PHP知道的响应代码相匹配。 You can't create your own response codes using this method, however you can using the header method. 您无法使用此方法创建自己的响应代码,但可以使用header方法。 Note also that http_response_code is only available in PHP 5.4.0 and higher. 另请注意, http_response_code仅适用于PHP 5.4.0及更高版本。

In summary - The differences between http_response_code and header for setting response codes: 总结 - http_response_codeheader之间的差异用于设置响应代码:

  1. Using http_response_code will cause PHP to match and apply a Reason Phrase from a list of Reason Phrases that are hard-coded into the PHP source code. 使用http_response_code将使PHP匹配并从原始短语列表中应用原因短语,这些原因短语被硬编码到PHP源代码中。

  2. Because of point 1 above, if you use http_response_code you must set a code that PHP knows about. 由于上面的第1点,如果您使用http_response_code ,则必须设置PHP知道的代码。 You can't set your own custom code, however you can set a custom code (and Reason Phrase) if you use the header function. 您无法设置自己的自定义代码,但是如果使用header功能,则可以设置自定义代码(和原因短语)。

  3. http_response_code is only available in PHP 5.4.0 and higher http_response_code仅适用于PHP 5.4.0及更高版本

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM