get_headers

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

向 URL 发请求并返回响应头数组(首元素是状态行),是轻量级 HTTP 探测的内置入口。

C C23

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

int main(void) {
    /* C 无标准库 HTTP 客户端:手写裸 TCP socket 发 HTTP/1.0 请求(最裸的对照) */
    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; /* 头部读完即可 */
    }
    close(fd);

    /* 状态行形如 "HTTP/1.1 200 OK",只提取三位状态码这个稳定派生事实 */
    const char *sp = strchr(buf, ' ');
    if (sp == NULL) return 1;
    printf("status: %.3s\n", sp + 1);
    return 0;
}
输出
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++ 同 C:标准库无 HTTP 客户端,手写裸 TCP socket(实战用 libcurl/httplib)
    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);

    // 状态行形如 "HTTP/1.1 200 OK",只提取三位状态码这个稳定派生事实
    size_t sp = buf.find(' ');
    if (sp == std::string::npos) return 1;
    std::cout << "status: " << buf.substr(sp + 1, 3) << "\n";
    return 0;
}
输出
status: 200

C# v11.0.100

v11.0.100
using System.Net.Http;

// HttpClient:StatusCode 枚举转 int 即状态码;resp.Headers 可枚举全部响应头(默认跟随重定向)
using var client = new HttpClient();
using var resp = await client.GetAsync("https://example.com");
Console.WriteLine($"status: {(int)resp.StatusCode}");
输出
status: 200

Go v1.27.4

v1.27.4
package main

import (
	"fmt"
	"net/http"
)

func main() {
	// http.Head 发 HEAD 请求;resp.Header 是响应头 map,StatusCode 即状态码(默认跟随重定向)
	resp, err := http.Head("https://example.com")
	if err != nil {
		fmt.Println("请求失败:", err)
		return
	}
	resp.Body.Close()
	fmt.Println("status:", resp.StatusCode)
}
输出
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() 即状态码,getHeaderFields() 是响应头 Map(默认同协议内跟随重定向)
        HttpURLConnection conn = (HttpURLConnection) new URL("https://example.com").openConnection();
        conn.setRequestMethod("GET");
        System.out.println("status: " + conn.getResponseCode());
        conn.disconnect();
    }
}
输出
status: 200

JavaScript v26.13.1

v26.13.1
// fetch:res.headers 是可迭代的 Headers 对象,res.status 即状态码(默认跟随重定向)
(async () => {
  const res = await fetch("https://example.com");
  console.log("status:", res.status);
})();
输出
status: 200

PHP v8.6.0

v8.6.0
// get_headers:返回含状态行的响应头数组;目标选 https://example.com(IANA 保留域,极稳定)
$headers = get_headers("https://example.com");
// 状态行前缀随 HTTP 版本漂移(HTTP/1.x vs HTTP/2)——只提取三位状态码这个稳定派生事实
preg_match('#^HTTP/\S+\s+(\d{3})#', $headers[0], $m);
echo "status: ", $m[1], "\n";
输出
status: 200

Python v3.15.2

v3.15.2
import urllib.request

# urllib:resp.status 即状态码,resp.headers 是响应头对象(默认跟随重定向)
with urllib.request.urlopen("https://example.com", timeout=10) as resp:
    print("status:", resp.status)
输出
status: 200

Rust v1.99.1

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

fn main() {
    // Rust 标准库无 HTTP/TLS 客户端:手写裸 TCP HTTP/1.0 请求(实战惯用 reqwest),
    // 端口 80 明文即可演示状态行解析
    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);
    // 状态行形如 "HTTP/1.1 200 OK",只提取三位状态码这个稳定派生事实
    let status = head
        .split("\r\n")
        .next()
        .and_then(|line| line.split_whitespace().nth(1))
        .unwrap_or("?");
    println!("status: {}", status);
}
输出
status: 200

TypeScript v26.13.1

v26.13.1
// fetch:res.headers 是可迭代的 Headers 对象,res.status 即状态码(默认跟随重定向)
(async () => {
  const res = await fetch("https://example.com");
  console.log("status:", res.status);
})();
输出
status: 200

语言差异说明

外部依赖稳定性前提(同 dns_get_record 条目):目标选 https://example.com(IANA 保留域,极稳定);状态行前缀随 HTTP 版本漂移(HTTP/1.x vs HTTP/2),所以示例只打印状态码这个稳定派生事实,绝不回填头原文。

C:无标准库 HTTP 客户端——示例手写裸 TCP socket 发 HTTP/1.0 请求自己解析状态行(最裸的对照,也正是 get_headers 底层做的事)。

C++:同 C;实战用 libcurl/Boost.Beast/httplib。

C#: HttpClient——resp.Headers(HttpHeaders 可枚举)+ resp.StatusCode;默认跟随重定向。

Go:net/http——resp.Header(map)+ resp.StatusCode;http.Head 发 HEAD 请求;默认跟随重定向(CheckRedirect 可关)。

Java:HttpURLConnection——getHeaderFields()(Map<String,List<String>>)+ getResponseCode();默认同协议内跟随重定向。

JavaScript:fetch——res.headers(Headers 可迭代)+ res.status;默认跟随重定向。

PHP:get_headers 返回含状态行的头数组($associative=true 时转键值映射);默认跟随重定向(stream 上下文 follow_location 可关);失败返回 false。

Python:urllib.request.urlopen——resp.headers(email.message.Message 对象)+ resp.status;默认跟随重定向。

Rust:标准库无 HTTP/TLS 客户端——示例手写裸 TCP(端口 80 明文演示);实战惯用 reqwest(默认跟随重定向)。

TypeScript:同 JavaScript(fetch + Headers)。