php取得請求url時回應的標頭資訊的方法:1、取url的時候,創建名為【$http_response_header】的變數來保存http回應的報頭;2、使用fopen開啟資料流訊息,用【stream_get_meta_data】取得。
php取得請求url時回應的標頭資訊的方法:
1、用file_get_contents
或fopen
、file
、readfile
等函數讀取url的時候,會建立一個名為$http_response_header
的變數來保存http回應的報頭.
範例程式碼一:
<?php $url = 'http://www.baidu.com'; $html = file_get_contents($url); print_r($http_response_header); //输出结果 Array( [0] => HTTP/1.1 200 OK [1] => Date: Tue, 06 Nov 2012 08:51:01 GMT [2] => Server: BWS/1.0 [3] => Content-Length: 9803 [4] => Content-Type: text/html;charset=gbk [5] => Cache-Control: private [6] => Expires: Tue, 06 Nov 2012 08:51:01 GMT [7] => Set-Cookie: BAIDUID=6635735B51B28640F425F802C49340F2:FG=1; expires=Tue, 06-Nov-42 08:51:01 GMT; path=/; domain=.baidu.com [8] => P3P: CP=" OTI DSP COR IVA OUR IND COM " [9] => Connection: Close ) ?>
2、使用fopen等函數開啟的資料流資訊可以用stream_get_meta_data
來取得。
範例程式碼二:
<?php $fp = fopen($url, 'r'); print_r(stream_get_meta_data($fp)); fclose($fp); //输出结果 Array ( [wrapper_data] => Array ( [0] => HTTP/1.1 200 OK [1] => Date: Tue, 06 Nov 2012 08:54:22 GMT [2] => Server: BWS/1.0 [3] => Content-Length: 9803 [4] => Content-Type: text/html;charset=gbk [5] => Cache-Control: private [6] => Expires: Tue, 06 Nov 2012 08:54:22 GMT [7] => Set-Cookie: BAIDUID=347578BCBD709F27925BDD8B05364A73:FG=1; expires=Tue, 06-Nov-42 08:54:22 GMT; path=/; domain=.baidu.com [8] => P3P: CP=" OTI DSP COR IVA OUR IND COM " [9] => Connection: Close ) [wrapper_type] => http [stream_type] => tcp_socket [mode] => r [unread_bytes] => 0 [seekable] => [uri] => http://www.baidu.com [timed_out] => [blocked] => 1 [eof] => ) ?>
3、get_headers()
也可以取得請求url的回應封包。
範例程式碼三:
<?php print_r(get_headers($url)); Array ( [0] => HTTP/1.1 200 OK [1] => Date: Tue, 06 Nov 2012 08:58:41 GMT [2] => Server: BWS/1.0 [3] => Content-Length: 9803 [4] => Content-Type: text/html;charset=gbk [5] => Cache-Control: private [6] => Expires: Tue, 06 Nov 2012 08:58:41 GMT [7] => Set-Cookie: BAIDUID=87B6F26EEC74F2B8F7FABA934DC6BB24:FG=1; expires=Tue, 06-Nov-42 08:58:41 GMT; path=/; domain=.baidu.com [8] => P3P: CP=" OTI DSP COR IVA OUR IND COM " [9] => Connection: Close ) ?>
相關學習推薦:php圖文教學
以上是php如何取得請求url時回應的報頭訊息的詳細內容。更多資訊請關注PHP中文網其他相關文章!