2

简短的问题:我可以依赖 , 等的行为header('.', TRUE, 404);header('.', TRUE, 501);

现在,让我详细说明。

在问我的问题之前,我将介绍header()调用的一些用法以及它生成的相应 HTTP 响应代码。

header('HTTP/1.1 404 Bummer!');--HTTP/1.1 404 Bummer!

header('HTTP/1.1 501 I am sick');--HTTP/1.1 501 I am sick

header('Bummer!', TRUE, 404);--HTTP/1.1 404 Not Found

header('I am sick', TRUE, 501);--HTTP/1.1 501 Method Not Implemented

因此,我们可以看到,如果我们使用第三个参数而第一个参数是垃圾,则忽略第一个参数。但是,http ://php.net/manual/en/function.header.php 上的文档说:

请注意,此参数仅在字符串不为空时才有效。

所以,我们仍然需要在第一个参数中添加一些东西。这对我来说有点难看,因为$string当我们在第三个参数中指定时忽略$http_response_code了它,但我们仍然需要为它设置一些值,$string即使它永远不会被使用。

但我能理解为什么会这样。传统上,header()只接受参数,我们可以像前两个示例一样设置任意响应代码。第二个和第三个参数是后来作为可选参数添加的。所以,如果我们想使用第二个和第三个参数,我们必须为第一个参数指定一些东西。此外,有时我们可能需要将有效的标头放在第一个参数中,同时将有效的响应代码放在第三个参数中。我在最后包括了一个这样的例子。

所以,我打算在我的代码中以这种方式使用这个函数:header('.', TRUE, 404);,header('.', TRUE, 501);等。根据上面的例子,它会按照标准产生正确的 HTTP 响应。我想知道我是否可以依赖这种行为。我问这个问题是因为我找不到明确提到$string当我们提供第三个参数 () 时第一个参数 () 将被忽略的文档$http_response_code

顺便说一句,我知道第一个参数在这种情况下很有用。

header('Foo: Bar', TRUE, 501);导致:

HTTP/1.1 501 Method Not Implemented
Date: Sun, 09 Oct 2011 19:01:19 GMT
Server: Apache/2.2.20 (Debian)
X-Powered-By: PHP/5.3.8-1
Foo: Bar
Vary: Accept-Encoding
Connection: close
Content-Type: text/html

一个更实际的例子是它会产生:header('Location: http://example.com/there/', TRUE, 307);

HTTP/1.1 307 Temporary Redirect
Date: Sun, 09 Oct 2011 19:09:29 GMT
Server: Apache/2.2.20 (Debian)
X-Powered-By: PHP/5.3.8-1
Location: http://example.com/there/
Vary: Accept-Encoding
Content-Type: text/html

无论如何,回到我的问题。我可以依赖 , 等的行为 header('.', TRUE, 404);header('.', TRUE, 501);

4

2 回答 2

3

不确定您是否正在寻找这个,但我想您不想构建 HTTP 状态行:

header('.', TRUE, 501);

让我的 Apache 返回此状态行:

HTTP/1.1 500 Internal Server Error

header(' ', TRUE, 501);

让我的 Apache 返回此状态行:

HTTP/1.1 501 Not Implemented

这可能是您正在寻找的。

也许你只是想建立状态线?

header('HTTP/1.1 501 No Implementation for you :)');

这使我的 Apache 返回此状态行:

HTTP/1.1 501 No Implementation for you :)

传统上,它是这样完成的:

header('HTTP/1.1 501');

然后得到一些默认状态行消息文本:

HTTP/1.1 501 Method Not Implemented

这不会更改协议版本:

header('HTTP/1.0 404');

因为它给出了:

HTTP/1.1 404 Not Found

希望这可以帮助。


苏萨姆更新:

使用 PHP 5.4,一个简单而优雅的方法是:

http_response_code(404);

或者

http_response_code(501);
于 2011-10-09T19:25:30.940 回答
1

There's currently no function to only set the numeric HTTP response code. However, I think PHP 5.4 will finally fill this void with http_response_code().

I wouldn't use header(".", TRUE, 501) myself. It might work on some web server software but very unlikely to work on them all.

于 2011-10-09T19:32:37.453 回答