$http_response_header 用法

今天在處理 '如何得到本地或遠程文件的 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);

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章