小编Ale*_*pov的帖子

为什么在 PHP 中的函数 header() 之后调用的函数 http_response_code() 表现得很奇怪?

出色地。我有一个问题http_response_code(),我找不到解释。如果我使用header()before http_response_code(),PHP 将返回由设置的 HTTP 状态header()并忽略任何http_response_code().

例如,我有一个文件:

<?php
header('HTTP/1.1 404 Not Found');
file_put_contents('./log',http_response_code(501).PHP_EOL,FILE_APPEND);
file_put_contents('./log',http_response_code(502).PHP_EOL,FILE_APPEND);
file_put_contents('./log',http_response_code(503).PHP_EOL,FILE_APPEND);

Run Code Online (Sandbox Code Playgroud)

(我用于file_put_contents()防止任何输出,因为有人可以说,这是这个问题的答案)

我使用默认的 php-server (但问题可以用 NGINX 重现):

<?php
header('HTTP/1.1 404 Not Found');
file_put_contents('./log',http_response_code(501).PHP_EOL,FILE_APPEND);
file_put_contents('./log',http_response_code(502).PHP_EOL,FILE_APPEND);
file_put_contents('./log',http_response_code(503).PHP_EOL,FILE_APPEND);

Run Code Online (Sandbox Code Playgroud)

有要求:

php -S localhost:9985
Run Code Online (Sandbox Code Playgroud)

有回应:

HTTP/1.1 404 Not Found
Host: localhost:9958
Date: Wed, 15 Sep 2021 17:20:05 GMT
Connection: close
X-Powered-By: PHP/8.0.10
Content-type: text/html; charset=UTF-8
Run Code Online (Sandbox Code Playgroud)

并且有日志:

404
501
502
Run Code Online (Sandbox Code Playgroud)

响应包括第一行:

HTTP/1.1 404 Not Found 
Run Code Online (Sandbox Code Playgroud)

但我在等待HTTP/1.1 503 Service Unavailable。日志文件包含预期数据,并显示http_response_code …

php fastcgi http-response-codes http-headers

5
推荐指数
1
解决办法
548
查看次数

标签 统计

fastcgi ×1

http-headers ×1

http-response-codes ×1

php ×1