gpt4 book ai didi

php - 在 PHP 中发送 HTTP 响应代码的最佳方式

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:41:09 24 4
gpt4 key购买 nike

通过阅读 php 规范和 Stack Overflow 上的其他问题,我可以看到三种从 PHP 发送 HTTP 响应代码的方法:

header("HTTP/1.0 404 Not Found");
^ ^ ^
A B C

header(" ", false, 404);
^ ^ ^
C D B

http_response_code(404);
^
B

A: Defines HTTP header
B: Response code
C: Message
D: To replace previous header or not

这些有什么区别,哪个最好用?我对参数的理解是否正确?

谢谢,

图兹里达。

最佳答案

为了回答您关于有何区别的问题,我找到了 this comment在 PHP 文档中(感谢 Steven):

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. Note that this means your response code must match a response code that PHP knows about. You can't create your own response codes using this method, however you can using the header method.

In summary - The differences between http_response_code and header for setting response codes:

  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.

  2. Because of point 1 above, if you use http_response_code you must set a code that PHP knows about. You can't set your own custom code, however you can set a custom code (and Reason Phrase) if you use the header method.


我很好奇一些流行的框架是如何在标准响应中发送 header 的:

Symfony (和 Laravel ,通过继承)设置原始 header :

// status
header(sprintf('HTTP/%s %s %s', $this->version, $this->statusCode, $this->statusText), true, $this->statusCode);

Zend Framework 2还设置原始 header :

public function renderStatusLine()
{
$status = sprintf(
'HTTP/%s %d %s',
$this->getVersion(),
$this->getStatusCode(),
$this->getReasonPhrase()
);
return trim($status);
}

Yii也是如此

protected function sendHeaders()
{
if (headers_sent()) {
return;
}
$statusCode = $this->getStatusCode();
header("HTTP/{$this->version} $statusCode {$this->statusText}");
// ...

关于php - 在 PHP 中发送 HTTP 响应代码的最佳方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30433288/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com