PHP URL函数

PHP get_headers() 函数返回一个数组,其中包含服务器响应 HTTP 请求而发送的标头。

语法

get_headers(url, associative, context) 

参数

url必填。 指定目标 URL。
associative可选。 如果设置为 true,此函数将解析响应并设置数组的键。
context可选。 指定使用 stream_context_create() 函数创建的上下文资源。

返回值

返回带有标头的索引数组或关联数组,失败时返回 false。

示例:get_headers() 示例

下面的示例显示了get_headers()函数的用法。

<?php
$url = "https://www.yxjc123.com";

//获取标头
$header = get_headers($url);

//显示结果
print_r($header);
?> 

上述代码的输出将是:

Array
(
    [0] => HTTP/1.1 200 OK
    [1] => Date: Sun, 26 Sep 2021 11:05:07 GMT
    [2] => Server: Apache/2.4.41 (Ubuntu)
    [3] => Set-Cookie: PHPSESSID=v2divqeg27m19balee6mmtmuas; path=/
    [4] => Expires: Thu, 19 Nov 1981 08:52:00 GMT
    [5] => Cache-Control: no-store, no-cache, must-revalidate
    [6] => Pragma: no-cache
    [7] => Vary: Accept-Encoding
    [8] => Connection: close
    [9] => Transfer-Encoding: chunked
    [10] => Content-Type: text/html; charset=UTF-8
) 

示例:使用关联参数

如果 associative 参数 设置为 true,该函数解析响应并设置数组的键。考虑下面的示例:

<?php
$url = "https://www.yxjc123.com";

//获取标头
$header = get_headers($url, true);

//显示结果
print_r($header);
?> 

上述代码的输出将是:

Array
(
    [0] => HTTP/1.1 200 OK
    [Date] => Sun, 26 Sep 2021 11:09:57 GMT
    [Server] => Apache/2.4.41 (Ubuntu)
    [Set-Cookie] => PHPSESSID=cbf8hu5i5j0enpth6pg4agifp4; path=/
    [Expires] => Thu, 19 Nov 1981 08:52:00 GMT
    [Cache-Control] => no-store, no-cache, must-revalidate
    [Pragma] => no-cache
    [Vary] => Accept-Encoding
    [Connection] => close
    [Transfer-Encoding] => chunked
    [Content-Type] => text/html; charset=UTF-8
)