http_get_last_response_headers

http_get_last_response_headers(): ?array

返回最近一次经 HTTP wrapper 接收的响应头索引数组(首行为 "HTTP/1.1 200 OK" 状态行),没有则返回 null。PHP >= 8.4.0 新增,替代自 8.4 起弃用的隐式变量 $http_response_header。CLI 下从未发出 HTTP 请求,恒 null——环境无关诚实演示。

C C23

C23
#include <stdio.h>
#include <string.h>

// C 标准库完全没有 HTTP 客户端:socket 要自己驱动,
// 响应头只是从字节流里解析出来的原始行
int main(void) {
    const char *raw =
        "HTTP/1.1 200 OK\r\n"
        "Content-Type: text/html\r\n"
        "Content-Length: 1256\r\n"
        "\r\n";
    int header_lines = 0;
    const char *p = raw;
    while (*p != '\0' && strncmp(p, "\r\n", 2) != 0) {
        const char *eol = strstr(p, "\r\n");
        if (eol == NULL) break;
        header_lines++;
        p = eol + 2;
    }
    printf("%d\n", header_lines);
    const char *ct = strstr(raw, "Content-Type: ");
    if (ct != NULL) {
        printf("%.*s\n", 9, ct + strlen("Content-Type: "));
    }
    return 0;
}
输出
3
text/html

C++ C++26

C++26
#include <cstring>
#include <iostream>
#include <sstream>
#include <string>

// C++ 标准库同样没有 HTTP 客户端:响应头块只能自己解析
int main() {
    const std::string raw =
        "HTTP/1.1 200 OK\r\n"
        "Content-Type: text/html\r\n"
        "Content-Length: 1256\r\n"
        "\r\n";
    std::istringstream in(raw);
    std::string line;
    int header_lines = 0;
    std::string content_type;
    while (std::getline(in, line) && line != "\r") {
        header_lines++;
        if (line.rfind("Content-Type: ", 0) == 0) {
            content_type = line.substr(strlen("Content-Type: "));
        }
    }
    std::cout << header_lines << "\n";
    std::cout << content_type << "\n";
    return 0;
}
输出
3
text/html

C# v11.0.100

v11.0.100
// C#:响应头是返回的 HttpResponseMessage 上的显式属性
using System.Net.Http;
using System.Net.Http.Headers;
var res = new HttpResponseMessage();
res.Headers.TryAddWithoutValidation("Server", "nginx");
res.Content = new StringContent("<html></html>");
res.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
var server = res.Headers.GetValues("Server");
Console.WriteLine(server.First());
Console.WriteLine(res.Content.Headers.ContentType);
Console.WriteLine(res.Headers.Contains("X-Missing"));
输出
nginx
text/html
False

Go v1.27.4

v1.27.4
package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"
)

// Go:响应头是返回的 *http.Response 上的显式字段
func main() {
	rec := httptest.NewRecorder()
	req := httptest.NewRequest("GET", "http://example.com/", nil)
	handler := func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "text/html")
		w.Header().Set("X-Cache", "HIT")
		fmt.Fprint(w, "<html></html>")
	}
	handler(rec, req)
	res := rec.Result()
	defer res.Body.Close()
	fmt.Println(res.Header.Get("Content-Type"))
	fmt.Println(res.Header.Get("X-Cache"))
	fmt.Println(res.Header.Get("X-Missing") == "")
}
输出
text/html
HIT
true

Java v27.0.1

v27.0.1
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class Main {
    // Java:响应头是调用的显式返回值
    // (HttpURLConnection.getHeaderFields() / HttpResponse.headers())
    static Map<String, List<String>> parseHeaders(String raw) {
        Map<String, List<String>> headers = new LinkedHashMap<>();
        for (String line : raw.split("\r\n")) {
            if (line.isEmpty() || line.startsWith("HTTP/")) continue;
            String[] kv = line.split(":", 2);
            headers.computeIfAbsent(kv[0].trim(), k -> new ArrayList<>()).add(kv[1].trim());
        }
        return headers;
    }
    public static void main(String[] args) {
        String raw = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nX-Cache: HIT\r\n\r\n";
        Map<String, List<String>> h = parseHeaders(raw);
        System.out.println(h.get("Content-Type").get(0));
        System.out.println(h.get("X-Cache").get(0));
        System.out.println(h.containsKey("X-Missing"));
    }
}
输出
text/html
HIT
false

JavaScript v26.13.1

v26.13.1
// JS:响应头是 fetch Response 对象上的显式属性
const res = new Response("<html></html>", {
  headers: { "Content-Type": "text/html", "X-Cache": "HIT" },
});
console.log(res.headers.get("content-type")); // Headers 查找大小写不敏感
console.log(res.headers.get("X-Cache"));
console.log(res.headers.get("X-Missing"));    // 不存在的头 -> null
输出
text/html
HIT
null

PHP v8.6.0

v8.6.0
// http_get_last_response_headers()(PHP >= 8.4.0):替代已弃用的
// $http_response_header 隐式变量;执行 file_get_contents('http://...') 后
// 它会是以 "HTTP/1.1 200 OK" 开头的索引 string[]
// CLI:从未跑过 HTTP wrapper 请求 -> null(环境无关事实)
var_dump(http_get_last_response_headers());
输出
NULL

Python v3.15.2

v3.15.2
# Python:响应头是客户端响应对象上的显式属性
#(requests.Response.headers / httpx.Response.headers / http.client getheaders());
# 标准库 email 消息容器离线模拟一个收到的头块
from email.parser import Parser
msg = Parser().parsestr("Content-Type: text/html\r\nX-Cache: HIT\r\n")
print(msg.get("Content-Type"))
print(msg.get("X-Cache"))
print(msg.get("X-Missing"))  # 不存在的头 -> None
输出
text/html
HIT
None

Rust v1.99.1

v1.99.1
// Rust:std 无 HTTP 客户端(reqwest/ureq 在 crate 层);
// 用标准库离线模拟一个收到的头块
use std::collections::HashMap;

fn parse_headers(raw: &str) -> HashMap<String, String> {
    let mut headers = HashMap::new();
    for line in raw.lines() {
        if line.is_empty() || line.starts_with("HTTP/") {
            continue;
        }
        if let Some((k, v)) = line.split_once(':') {
            headers.insert(k.trim().to_string(), v.trim().to_string());
        }
    }
    headers
}

fn main() {
    let raw = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nX-Cache: HIT\r\n\r\n";
    let h = parse_headers(raw);
    println!("{}", h.get("Content-Type").map(String::as_str).unwrap_or("(null)"));
    println!("{}", h.get("X-Cache").map(String::as_str).unwrap_or("(null)"));
    println!("{}", h.contains_key("X-Missing"));
}
输出
text/html
HIT
false

TypeScript v26.13.1

v26.13.1
// TS:响应头类型由 Response['headers'] Headers 接口标注
const res: Response = new Response("<html></html>", {
  headers: { "Content-Type": "text/html", "X-Cache": "HIT" },
});
console.log(res.headers.get("content-type")); // Headers 查找大小写不敏感
console.log(res.headers.get("X-Cache"));
console.log(res.headers.get("X-Missing"));    // 不存在的头 -> null
输出
text/html
HIT
null

语言差异说明

C:标准库无 HTTP 客户端,socket 层拿到的是原始字节流,响应头只能自己切行解析;libcurl 是第三方库。

C++:同 C,std 无 HTTP 客户端;cpp-httplib 等是第三方。

C#:响应头是 HttpResponseMessage 的显式属性(res.Headers/res.Content.Headers)。

Go:响应头是 *http.Response 的显式字段 resp.Header;示例用 httptest 离线构造。

Java:显式返回——老 HttpURLConnection.getHeaderFields()(注意返回 Map 里含 null 键的状态行)与新 java.net.http.HttpResponse.headers()。

JavaScript:语言自带 fetch 的 Response.headers(Headers 对象,大小写不敏感查找)。

PHP:核实手册为 PHP >= 8.4.0 新增(非简报所写 8.5),替代自 8.4 起弃用的隐式变量 $http_response_header——旧变量是在发起 HTTP 请求的局部作用域里隐式创建的,因此无法用用户态函数 polyfill 本函数;返回索引数组(非关联数组),首元素是 "HTTP/1.1 200 OK" 状态行;从未经 HTTP wrapper 发过请求时返回 null,CLI 下恒 null(环境无关事实);配套 http_clear_last_response_headers() 清除。

Python:第三方 requests/httpx 的 Response.headers(大小写不敏感 dict 视图);标准库 http.client 用 getheaders() 返回 list[tuple]。

Rust:std 无 HTTP 客户端;reqwest/ureq 在 crate 层,响应头同样是显式字段。

TypeScript:同 JavaScript。

—— 教学闭环:PHP 曾把响应头塞进「隐式变量」(8.4 弃用)→ 8.4 改成显式函数返回;而各语言从一开始就是「响应对象是调用的显式返回值」——本条目是「隐式上下文 vs 显式返回」设计哲学的活教材。