phpinfo()以一种奇怪的方式改变nginx响应的状态码

62o28rlo  于 2022-10-30  发布在  PHP
关注(0)|答案(1)|浏览(135)

我有一个php代码,应该总是结束“http 500代码”,因为我有一个未定义的func status_code("OK");调用

代码

<?

# phpinfo();

echo 'error_log = ' . ini_get('error_log') . "\n";
status_code("OK");
echo "OK";
?>

以上示例:

➜ curl -I http://localhost:8080/kkk
HTTP/1.1 500 Internal Server Error
Server: nginx/1.20.1
Date: Sat, 29 Oct 2022 18:48:25 GMT
Content-Type: text/html
Content-Length: 5597
Connection: close
ETag: "635c9b20-15dd"

在stdout输出中:

2022/10/29 18:50:32 [error] 29#29: *30 FastCGI sent in stderr: "PHP message: PHP Fatal error:  Uncaught Error: Call to undefined function status_code() in /legacy/app/index.php:4
Stack trace:

# 0 {main}

  thrown in /legacy/app/index.php on line 4" while reading response header from upstream, client: 172.17.0.1, server: localhost, request: "HEAD /kkk HTTP/1.1", upstream: "fastcgi://127.0.0.1:9000", host: "localhost:8080"
172.17.0.1 - - [29/Oct/2022:18:50:32 +0000] 500 "HEAD /kkk HTTP/1.1" 0 "-" "curl/7.82.0" "-"

但是,如果我取消注解#phpinfo();行,我会得到200 OK:

➜ curl -I http://localhost:8080/kkk
HTTP/1.1 200 OK
Server: nginx/1.20.1
Date: Sat, 29 Oct 2022 18:52:25 GMT
Content-Type: text/html; charset=UTF-8
Connection: keep-alive
X-Powered-By: PHP/7.1.33

在stdout中:

172.17.0.1 - - [29/Oct/2022:18:52:25 +0000] 200 "HEAD /kkk HTTP/1.1" 0 "-" "curl/7.82.0" "-"

我正在运行nginx,它具有以下配置:

location ~ \.php$ {
    root /legacy/app;
    fastcgi_pass 127.0.0.1:9000;
    fastcgi_read_timeout 10s;
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    fastcgi_index index.php;
    fastcgi_intercept_errors on;
    fastcgi_buffer_size 16k;
    fastcgi_buffers 4 16k;
}

location / {
    # make sure you have a custom html page placed in app folder
    # i.e. /legacy/app/app/50x.html
    try_files _ /index.php?$query_string;

}
jk9hmnmh

jk9hmnmh1#

您应该使用内置函数http_response_code()来更改响应代码。
但是,和header()一样,您必须phpinfo()之前调用http_response_code(),因为您的响应中产生的任何输出都意味着带有200状态代码的头,您不能再更改它了。(请参见Call header() after output is sent
刚刚测试了Apache(我不认为这有什么区别)。
工作(显示php信息与500状态码):

http_response_code(500);
phpinfo();

这 * 不起作用 *(显示带有200状态码的php信息):

phpinfo();
http_response_code(500);

这 * 不起作用 *(显示带有200状态码的php信息):

phpinfo();
undefined_function(); // generates an error in error.log

相关问题