ZetCode

PHP http_get_last_response_headers 函数

最后修改于 2025 年 4 月 4 日

PHP http_get_last_response_headers 函数检索最后一次请求的 HTTP 响应头。它对于调试和处理 Web 响应非常有用。

基本定义

http_get_last_response_headers 返回最近一次 HTTP 请求的响应头数组。适用于 HTTP 扩展函数。

语法:http_get_last_response_headers(): array|null。如果未进行请求,则返回头信息的关联数组或 null。需要 pecl_http 扩展。

基本头信息检索

此示例展示了如何获取和显示简单 HTTP 请求的所有响应头。

basic_headers.php
<?php

declare(strict_types=1);

http_get("https://example.com");
$headers = http_get_last_response_headers();

print_r($headers);

此示例向 example.com 发送 GET 请求,然后检索所有响应头。头信息以数组格式打印,显示键和值。

检查特定头信息

此示例演示如何检查响应中的特定头信息(Content-Type)。

content_type_check.php
<?php

declare(strict_types=1);

http_get("https://example.com");
$headers = http_get_last_response_headers();

if (isset($headers['Content-Type'])) {
    echo "Content-Type: " . $headers['Content-Type'];
} else {
    echo "Content-Type header not found";
}

此示例检查响应中是否存在 Content-Type 头信息。Content-Type 指示返回资源的媒体类型。

处理所有头信息

此示例在 foreach 循环中处理响应的所有头信息。

process_headers.php
<?php

declare(strict_types=1);

http_get("https://example.com");
$headers = http_get_last_response_headers();

foreach ($headers as $name => $value) {
    echo "$name: $value\n";
}

此示例遍历所有响应头,显示每个名称-值对。这对于调试或记录完整的头信息很有用。

检查响应状态

此示例展示了如何从响应头中验证 HTTP 状态码。

status_check.php
<?php

declare(strict_types=1);

http_get("https://example.com");
$headers = http_get_last_response_headers();

if (isset($headers['Status'])) {
    echo "Response status: " . $headers['Status'];
} else {
    echo "Status header not found";
}

Status 头信息包含 HTTP 响应状态码。这有助于确定请求是否成功或遇到了错误。

头信息大小写敏感性

此示例演示了 PHP 中头信息的名称大小写敏感性。

header_case.php
<?php

declare(strict_types=1);

http_get("https://example.com");
$headers = http_get_last_response_headers();

$contentType1 = $headers['Content-Type'] ?? 'Not found';
$contentType2 = $headers['content-type'] ?? 'Not found';

echo "Content-Type: $contentType1\n";
echo "content-type: $contentType2\n";

HTTP 中的头信息名称不区分大小写,但 PHP 会保留原始的大小写。此示例展示了在检查头信息时如何处理这两种情况。

最佳实践

来源

PHP http_get_last_response_headers 文档

本教程通过实际示例介绍了 PHP http_get_last_response_headers 函数在 PHP 中处理 HTTP 头信息。

作者

我叫 Jan Bodnar,我是一名充满热情的程序员,拥有丰富的编程经验。我从 2007 年开始撰写编程文章。迄今为止,我已撰写了 1400 多篇文章和 8 本电子书。我在教授编程方面拥有十多年的经验。

列出 所有 PHP 网络函数