PHP file_get_contents 判断是否获取成功,查看请求返回头信息

PHP 简单快速的获取文件信息,可以用函数 file_get_contents(),包括网络文件信息,当然file_get_contents()也有许多不稳定的因素,先来讲获取请求返回头信息 ;

示例:

  1. <?php  
  2.   
  3.    //加上@ 是为了防止file_get_contents获取失败返回至命错误,影响后面的程序运行   
  4.   
  5.    @file_get_contents("http://tqybw.net");     
  6.    var_dump($http_response_header);   
  7.    //<VAR class=varname><VAR class=varname>$http_response_header</VAR></VAR> <SPAN class=type><SPAN class="type 数组">数组</SPAN></SPAN>与 <SPAN class=function>get_headers()</SPAN> 函数类似。当使用HTTP 包装器时,<VAR class=varname><VAR class=varname>$http_response_header</VAR></VAR> 将会被 HTTP 响应头信息填充。<VAR class=varname><VAR class=varname>    $http_response_header</VAR></VAR> 将被创建于局部作用域中。     
  8.   
  9. ?>  
  10.   
  11. //输出结果   
  12.   
  13.   array(9) {     
  14.      [0]=>     
  15.      string(15) "HTTP/1.1 200 OK"  //这个很关键,通过返回状态码可以得知是否成功   
  16.       [1]=>     
  17.      string(35) "Date: Sat, 12 Apr 2012 17:30:38 GMT"    
  18.      [2]=>     
  19.      string(29) "Server: Apache/2.2.3 (CentOS)"    
  20.      [3]=>     
  21.      string(44) "Last-Modified: Tue, 15 Nov 2005 13:24:10 GMT"    
  22.      [4]=>     
  23.      string(27) "ETag: "280100-1b6-80bfd280""    
  24.      [5]=>     
  25.      string(20) "Accept-Ranges: bytes"    
  26.      [6]=>     
  27.      string(19) "Content-Length: 438"    
  28.      [7]=>     
  29.      string(17) "Connection: close"    
  30.      [8]=>     
  31.      string(38) "Content-Type: text/html; charset=UTF-8"    
  32.   }    
<?php

   //加上@ 是为了防止file_get_contents获取失败返回至命错误,影响后面的程序运行

   @file_get_contents("http://tqybw.net");   
   var_dump($http_response_header); 
   //$http_response_header 数组get_headers() 函数类似。当使用HTTP 包装器时,$http_response_header 将会被 HTTP 响应头信息填充。    $http_response_header 将被创建于局部作用域中。  

?>

//输出结果

  array(9) {   
     [0]=>   
     string(15) "HTTP/1.1 200 OK"  //这个很关键,通过返回状态码可以得知是否成功
      [1]=>   
     string(35) "Date: Sat, 12 Apr 2012 17:30:38 GMT"  
     [2]=>   
     string(29) "Server: Apache/2.2.3 (CentOS)"  
     [3]=>   
     string(44) "Last-Modified: Tue, 15 Nov 2005 13:24:10 GMT"  
     [4]=>   
     string(27) "ETag: "280100-1b6-80bfd280""  
     [5]=>   
     string(20) "Accept-Ranges: bytes"  
     [6]=>   
     string(19) "Content-Length: 438"  
     [7]=>   
     string(17) "Connection: close"  
     [8]=>   
     string(38) "Content-Type: text/html; charset=UTF-8"  
  }  

注意:

1、file_get_contents 用于获取网络文件时,如:(file_get_contents("http://tqybw.net/beijing15tian/")),不能频繁使用,特别是网络不稳定时,容易造成超时引起服务占资源

2、file_get_contents 获取文件大小有限制
 
posted @ 2014-05-11 10:17  stma  阅读(2508)  评论(0)    收藏  举报