http_get_last_response_headers

http_get_last_response_headers(): ?array

Returns the indexed array of headers from the most recent HTTP-wrapper response (first entry is the "HTTP/1.1 200 OK" status line), or null if there were none. Added in PHP >= 8.4.0 as the replacement for the implicit $http_response_header variable deprecated since 8.4. Under CLI no HTTP request has ever been made, so it is always null - an honest environment-independent demo.

C C23

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

// C has no HTTP client in the standard library at all: you drive sockets yourself,
// so response headers are just raw lines you parse out of the byte stream
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;
}
Output
3
text/html

C++ C++26

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

// C++ has no HTTP client in std either: parse the raw header block yourself
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;
}
Output
3
text/html

C# v11.0.100

v11.0.100
// C#: response headers are an explicit property of the returned 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"));
Output
nginx
text/html
False

Go v1.27.4

v1.27.4
package main

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

// Go: response headers are an explicit field on the returned *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") == "")
}
Output
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: response headers are an explicit return of the call
    // (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"));
    }
}
Output
text/html
HIT
false

JavaScript v26.13.1

v26.13.1
// JS: response headers are an explicit property of the fetch Response object
const res = new Response("<html></html>", {
  headers: { "Content-Type": "text/html", "X-Cache": "HIT" },
});
console.log(res.headers.get("content-type")); // Headers lookup is case-insensitive
console.log(res.headers.get("X-Cache"));
console.log(res.headers.get("X-Missing"));    // absent header -> null
Output
text/html
HIT
null

PHP v8.6.0

v8.6.0
// http_get_last_response_headers() (PHP >= 8.4.0): replaces the deprecated
// $http_response_header implicit variable; after file_get_contents('http://...')
// it would be an indexed string[] starting with "HTTP/1.1 200 OK"
// CLI: no HTTP wrapper request has ever run -> null (environment-independent fact)
var_dump(http_get_last_response_headers());
Output
NULL

Python v3.15.2

v3.15.2
# Python: response headers are an explicit property of the client response object
# (requests.Response.headers / httpx.Response.headers / http.client getheaders());
# the stdlib email message container models a received header block offline
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"))  # absent header -> None
Output
text/html
HIT
None

Rust v1.99.1

v1.99.1
// Rust: no HTTP client in std (reqwest/ureq live at the crate layer);
// offline stdlib model of a received header block
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"));
}
Output
text/html
HIT
false

TypeScript v26.13.1

v26.13.1
// TS: response headers typed via the Response['headers'] Headers interface
const res: Response = new Response("<html></html>", {
  headers: { "Content-Type": "text/html", "X-Cache": "HIT" },
});
console.log(res.headers.get("content-type")); // Headers lookup is case-insensitive
console.log(res.headers.get("X-Cache"));
console.log(res.headers.get("X-Missing"));    // absent header -> null
Output
text/html
HIT
null

Language differences

C: the stdlib has no HTTP client - the socket layer hands you raw bytes, so response headers can only be parsed line by line yourself; libcurl is third-party.

C++: same as C, no HTTP client in std; cpp-httplib and friends are third-party.

C#: headers are explicit properties of HttpResponseMessage (res.Headers/res.Content.Headers).

Go: headers are the explicit resp.Header field on *http.Response; the demo builds one offline with httptest.

Java: explicit returns - the legacy HttpURLConnection.getHeaderFields() (note the Map contains a null-keyed status line) and the modern java.net.http.HttpResponse.headers().

JavaScript: the language ships fetch's Response.headers (a Headers object with case-insensitive lookup).

PHP: verified against the manual as added in PHP >= 8.4.0 (not 8.5 as the brief assumed) - the replacement for the implicit $http_response_header variable deprecated since 8.4; the old variable was created implicitly in the LOCAL scope of the code that issued the HTTP request, so this function cannot be polyfilled in userland; it returns an INDEXED array (not associative) whose first entry is the "HTTP/1.1 200 OK" status line; returns null when no HTTP-wrapper request has been made, and is always null under CLI (environment-independent fact); http_clear_last_response_headers() is the companion.

Python: requests/httpx expose Response.headers (a case-insensitive dict view); the stdlib http.client uses getheaders() returning list[tuple].

Rust: no HTTP client in std; reqwest/ureq live at the crate layer, where headers are likewise explicit fields.

TypeScript: same as JavaScript.

- Teaching closure: PHP once stuffed response headers into an "implicit variable" (deprecated in 8.4) and 8.4 turned it into an explicit function return; every other language was "the response object is the explicit return value of the call" from day one - this entry is a living lesson in implicit-context vs explicit-return design philosophy.