get_headers

get_headers(string $url, bool $associative = false, ?resource $context = null): array|false

Sends a request to a URL and returns the response headers as an array (the first element is the status line) — the built-in lightweight HTTP probe.

C C23

C23
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>

int main(void) {
    /* C has no standard HTTP client: hand-write a raw TCP socket sending an HTTP/1.0 request (the barest possible counterpart) */
    struct addrinfo hints = {0}, *res;
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    if (getaddrinfo("example.com", "80", &hints, &res) != 0) return 1;
    int fd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
    if (fd < 0 || connect(fd, res->ai_addr, res->ai_addrlen) != 0) return 1;
    freeaddrinfo(res);
    const char *req = "GET / HTTP/1.0\r\nHost: example.com\r\n\r\n";
    if (write(fd, req, strlen(req)) < 0) return 1;

    char buf[4096];
    size_t len = 0;
    buf[0] = '\0';
    while (len < sizeof(buf) - 1) {
        ssize_t n = read(fd, buf + len, sizeof(buf) - 1 - len);
        if (n <= 0) break;
        len += (size_t)n;
        buf[len] = '\0';
        if (strstr(buf, "\r\n\r\n")) break; /* Stop once the headers are read */
    }
    close(fd);

    /* The status line looks like "HTTP/1.1 200 OK"; extract only the three-digit status code, the stable derived fact */
    const char *sp = strchr(buf, ' ');
    if (sp == NULL) return 1;
    printf("status: %.3s\n", sp + 1);
    return 0;
}
Output
status: 200

C++ C++26

C++26
#include <cstring>
#include <iostream>
#include <netdb.h>
#include <string>
#include <sys/socket.h>
#include <unistd.h>

int main() {
    // C++ same as C: no standard HTTP client, hand-write a raw TCP socket (libcurl/httplib in real projects)
    addrinfo hints{};
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    addrinfo *res = nullptr;
    if (getaddrinfo("example.com", "80", &hints, &res) != 0) return 1;
    int fd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
    if (fd < 0 || connect(fd, res->ai_addr, res->ai_addrlen) != 0) return 1;
    freeaddrinfo(res);
    const std::string req = "GET / HTTP/1.0\r\nHost: example.com\r\n\r\n";
    if (write(fd, req.data(), req.size()) < 0) return 1;

    std::string buf;
    char chunk[1024];
    while (buf.find("\r\n\r\n") == std::string::npos) {
        ssize_t n = read(fd, chunk, sizeof chunk);
        if (n <= 0) break;
        buf.append(chunk, chunk + n);
    }
    close(fd);

    // The status line looks like "HTTP/1.1 200 OK"; extract only the three-digit status code, the stable derived fact
    size_t sp = buf.find(' ');
    if (sp == std::string::npos) return 1;
    std::cout << "status: " << buf.substr(sp + 1, 3) << "\n";
    return 0;
}
Output
status: 200

C# v11.0.100

v11.0.100
using System.Net.Http;

// HttpClient: cast the StatusCode enum to int for the status code; resp.Headers enumerates all response headers (redirects followed by default)
using var client = new HttpClient();
using var resp = await client.GetAsync("https://example.com");
Console.WriteLine($"status: {(int)resp.StatusCode}");
Output
status: 200

Go v1.27.4

v1.27.4
package main

import (
	"fmt"
	"net/http"
)

func main() {
	// http.Head sends a HEAD request; resp.Header is the header map, StatusCode is the code (redirects followed by default)
	resp, err := http.Head("https://example.com")
	if err != nil {
		fmt.Println("请求失败:", err)
		return
	}
	resp.Body.Close()
	fmt.Println("status:", resp.StatusCode)
}
Output
status: 200

Java v27.0.1

v27.0.1
import java.net.HttpURLConnection;
import java.net.URL;

public class Main {
    public static void main(String[] args) throws Exception {
        // HttpURLConnection: getResponseCode() is the status code, getHeaderFields() the header Map (same-protocol redirects followed by default)
        HttpURLConnection conn = (HttpURLConnection) new URL("https://example.com").openConnection();
        conn.setRequestMethod("GET");
        System.out.println("status: " + conn.getResponseCode());
        conn.disconnect();
    }
}
Output
status: 200

JavaScript v26.13.1

v26.13.1
// fetch: res.headers is an iterable Headers object, res.status is the code (redirects followed by default)
(async () => {
  const res = await fetch("https://example.com");
  console.log("status:", res.status);
})();
Output
status: 200

PHP v8.6.0

v8.6.0
// get_headers: returns the response header array including the status line; target https://example.com (an IANA reserved domain, extremely stable)
$headers = get_headers("https://example.com");
// The status-line prefix drifts with the HTTP version (HTTP/1.x vs HTTP/2) — extract only the three-digit status code, the stable derived fact
preg_match('#^HTTP/\S+\s+(\d{3})#', $headers[0], $m);
echo "status: ", $m[1], "\n";
Output
status: 200

Python v3.15.2

v3.15.2
import urllib.request

# urllib: resp.status is the code, resp.headers the header object (redirects followed by default)
with urllib.request.urlopen("https://example.com", timeout=10) as resp:
    print("status:", resp.status)
Output
status: 200

Rust v1.99.1

v1.99.1
use std::io::{Read, Write};
use std::net::TcpStream;

fn main() {
    // No HTTP/TLS client in Rust's standard library: hand-write a raw TCP HTTP/1.0 request (reqwest is idiomatic in real projects),
    // plain port 80 is enough to demo status-line parsing
    let mut stream = TcpStream::connect("example.com:80").expect("connect failed");
    stream
        .write_all(b"GET / HTTP/1.0\r\nHost: example.com\r\n\r\n")
        .unwrap();
    let mut buf = Vec::new();
    let mut chunk = [0u8; 1024];
    while !buf.windows(4).any(|w| w == b"\r\n\r\n") {
        let n = stream.read(&mut chunk).unwrap();
        if n == 0 {
            break;
        }
        buf.extend_from_slice(&chunk[..n]);
    }
    let head = String::from_utf8_lossy(&buf);
    // The status line looks like "HTTP/1.1 200 OK"; extract only the three-digit status code, the stable derived fact
    let status = head
        .split("\r\n")
        .next()
        .and_then(|line| line.split_whitespace().nth(1))
        .unwrap_or("?");
    println!("status: {}", status);
}
Output
status: 200

TypeScript v26.13.1

v26.13.1
// fetch: res.headers is an iterable Headers object, res.status is the code (redirects followed by default)
(async () => {
  const res = await fetch("https://example.com");
  console.log("status:", res.status);
})();
Output
status: 200

Language differences

External-dependency stability premise (same as the dns_get_record entry): the target is https://example.com (an IANA-reserved domain, extremely stable); the status line's prefix drifts with the HTTP version (HTTP/1.x vs HTTP/2), so the examples print only the status code — a stable derived fact — never the raw headers.

C: no standard HTTP client — the example hand-writes a raw TCP socket with an HTTP/1.0 request and parses the status line itself (the barest contrast, and exactly what get_headers does under the hood).

C++: same as C; real work uses libcurl/Boost.Beast/httplib.

C#: HttpClient — resp.Headers (an enumerable HttpHeaders) + resp.StatusCode; follows redirects by default.

Go: net/http — resp.Header (a map) + resp.StatusCode; http.Head sends a HEAD request; redirects followed by default (disable via CheckRedirect).

Java: HttpURLConnection — getHeaderFields() (Map<String,List<String>>) + getResponseCode(); same-protocol redirects followed by default.

JavaScript: fetch — res.headers (an iterable Headers) + res.status; follows redirects by default.

PHP: get_headers returns the header array with the status line first ($associative=true turns it into a key-value map); redirects followed by default (disable via the stream context's follow_location); returns false on failure.

Python: urllib.request.urlopen — resp.headers (an email.message.Message) + resp.status; follows redirects by default.

Rust: no HTTP/TLS client in std — the example hand-writes raw TCP (plaintext port 80 for the demo); reqwest is the usual pick in real work (follows redirects by default).

TypeScript: same as JavaScript (fetch + Headers).