今天在处理 '如何得到本地或远程文件的 MIME 类型' 问题时,了解到了 '$http_response_header',之前可能也见到过,但一定是完全没注意过,没想到还有点意思,记录下,也给大家分享下这个知识点。
$http_response_header
首先看官方文档:
https://www.php.net/manual/zh/reserved.variables.httpresponseheader.php
同我们熟知的 $GLOBALS, $_SERVER, $_GET ... 都是 '预定义变量'(正好我们也可以仔细看下 PHP 所有的预定义变量,以及其他几个特殊的预定义变量的用法)
查看说明,我们一句一句分析:
1.$http_response_header 数组与 'get_headers()' 函数类似
我们来看下 get_headers() 函数:
get_headers($url[, $format = 0]) - 请求一个 url,不获取内容,只得到 HTTP 响应头
$format 参数,只是返回不同格式的数组:
0 - [
[0] => HTTP/1.1 200 OK
[1] => Content-Type: text/html
...
]
1 - [
[0] => HTTP/1.1 200 OK
[Content-Type] => text/html
...
]
所以我们知道,get_headers() 就是只获取远程地址 HTTP 响应头
2.当使用 'HTTP 包装器' 时,$http_response_header 将会被 HTTP 响应头信息填充。
HTTP 包装器是什么,我们继续查看文档(这部分属于 '支持的协议和封装协议'):
http 和 https 协议 - 就是访问远程的 http/https 网址
只要在 PHP 内,调用内置的部分函数请求了远程地址,就会自动将 HTTP 响应头填充到 $http_response_header 变量中
哪些函数调用可以得到 $http_response_header,目前了解到的有:
fopen
file_get_contents
copy(远程文件地址, 本地系统文件地址)
注意 curl 扩展,不会得到 $http_response_header
测试示例:
1.fopen()
$url = 'http://www.xxx.com/a.jpg';
fopen($url, 'r');
var_dump($http_response_header);
2.file_get_contents()
$url = 'http://www.xxx.com/a.jpg';
file_get_contents($url);
var_dump($http_response_header);
3.copy()
$url = 'http://www.xxx.com/a.jpg';
copy($url, $local_destination_path);
var_dump($http_response_header);