php get_headers函数的作用及用法
封面图
•
2025-11-02
•
PHP
198
0
0
0
在 PHP 中,`get_headers()` 函数用于获取一个 HTTP 响应头信息。它通常用于检查远程服务器返回的 HTTP 头信息,例如状态码、内容类型、内容长度等。 --- ## ✅ 一、函数作用 `get_headers()` 的主要作用是: - 获取指定 URL 的 HTTP 响应头(包括状态码)。 - 可以用于验证 URL 是否有效、判断文件是否存在、检查响应状态码等。 --- ## ✅ 二、函数语法 ```php array get_headers(string $url, int $format = 0) ``` ### 参数说明: - `$url`:要获取头部信息的 URL 地址。 - `$format`:可选参数,设置返回格式: - `0`(默认):返回一个数组,每个元素是一个字符串。 - `1`:返回一个关联数组,键为字段名,值为字段值。 --- ## ✅ 三、示例用法 ### 示例 1:基本使用(返回字符串数组) ```php $headers = get_headers("https://www.example.com"); foreach ($headers as $header) { echo $header . "<br>"; } ``` 输出可能类似: ``` HTTP/1.1 200 OK Date: Mon, 05 Jun 2023 12:34:56 GMT Server: Apache Content-Type: text/html; charset=UTF-8 ... ``` --- ### 示例 2:使用关联数组格式(`$format = 1`) ```php $headers = get_headers("https://www.example.com", 1); print_r($headers); ``` 输出可能类似: ```php Array ( [0] => HTTP/1.1 200 OK [Date] => Mon, 05 Jun 2023 12:34:56 GMT [Server] => Apache [Content-Type] => text/html; charset=UTF-8 ... ) ``` --- ## ✅ 四、注意事项 1. **需要启用 `allow_url_fopen`**:PHP 默认允许通过 `get_headers()` 访问远程 URL,但如果你的服务器禁用了这个功能,可能会报错。可以在 `php.ini` 中开启: ```ini allow_url_fopen = On ``` 2. **超时设置**:如果访问的 URL 很慢或无法访问,可以使用 `stream_context_create()` 设置超时时间: ```php $context = stream_context_create([ 'http' => [ 'timeout' => 5 // 超时时间(秒) ] ]); $headers = get_headers("https://example.com", 1, $context); ``` 3. **HTTPS 支持**:确保 PHP 安装了 `openssl` 扩展,否则可能无法访问 HTTPS 网站。 --- ## ✅ 五、常见用途 - 检查页面是否可访问(状态码是否为 200)。 - 获取文件大小(`Content-Length`)。 - 判断内容类型(`Content-Type`)。 - 验证缓存(如 `Last-Modified`、`ETag`)。 - 检测重定向(如 301、302 状态码)。 --- ## ✅ 六、示例:检查页面是否可用 ```php $headers = get_headers("https://example.com", 1); if (strpos($headers['Status'], '200') !== false) { echo "页面可用"; } else { echo "页面不可用"; } ``` --- 如果你还有其他关于 PHP 函数的问题,欢迎继续提问!
上一篇:
php namespace用法
下一篇:
php 采集curl_init抓取网页内容
标题录入,一次不能超过6条
留言
评论