首页 >后端开发 >PHP问题 >php如何获取请求url时响应的报头信息

php如何获取请求url时响应的报头信息

coldplay.xixi
coldplay.xixi原创
2020-08-03 13:31:033528浏览

php获取请求url时响应的报头信息的方法:1、取url的时候,创建名为【$http_response_header】的变量来保存http响应的报头;2、使用fopen打开数据流信息,用【stream_get_meta_data】获取。

php如何获取请求url时响应的报头信息

php获取请求url时响应的报头信息的方法:

1、用file_get_contents或者fopenfilereadfile等函数读取url的时候,会创建一个名 为$http_response_header的变量来保存http响应的报头.

示例代码一:

<?php 
       $url = &#39;http://www.baidu.com&#39;; 
       $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, &#39;r&#39;); 
     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中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn