您好,欢迎访问一九零五行业门户网

PHP使用get_headers函数判断远程文件是否存在的方法,_PHP教程

php使用get_headers函数判断远程文件是否存在的方法,本文实例讲述了php使用get_headers函数判断远程文件是否存在的方法。分享给大家供大家参考。具体实现方法如下:
以前讲过程关于php判断远程文件是否存在的文章都是利用fopen,sockt,curl函数来实现检查远程文件是否存在,下面我再介绍利用 get_headers来检查远程文件是否存在,感兴趣的朋友可以参考一下。
先来简单了解get_headers()函数
get_headers() 返回一个数组m包含有服务器响应一个 http 请求所发送的标头。
get_headers:发送服务器响应http请求
get_headers(字符串url[链接格式])
get_headers()以数组的形式返回服务器http请求m如果执行失败,将返回false和一个错误的水平e_warning,
可选参数设置为1,get_headers()能分析系统的响应速度和集数组中的键,
注意:使用该函数需要把 php.ini里面的allow_url_fopen = on,才能使用
实例代码如下:
复制代码 代码如下:
$url = 'http://www.bkjia.com';
print_r(get_headers($url));
print_r(get_headers($url, 1));
?>
运行结果如下:
复制代码 代码如下:
array
(
    [0] => http/1.1 200 ok
    [1] => cache-control: max-age=1800
    [2] => content-length: 54874
    [3] => content-type: text/html
    [4] => content-location: http://www.bkjia.com/index.htm
    [5] => last-modified: fri, 28 nov 2014 03:34:56 gmt
    [6] => accept-ranges: bytes
    [7] => etag: b66ba847bcad01:bc5
    [8] => server: microsoft-iis/6.0
    [9] => date: fri, 28 nov 2014 03:37:34 gmt
    [10] => connection: close
)
array
(
    [0] => http/1.1 200 ok
    [cache-control] => max-age=1800
    [content-length] => 54874
    [content-type] => text/html
    [content-location] => http://www.bkjia.com/index.htm
    [last-modified] => fri, 28 nov 2014 03:34:56 gmt
    [accept-ranges] => bytes
    [etag] => b66ba847bcad01:bc5
    [server] => microsoft-iis/6.0
    [date] => fri, 28 nov 2014 03:37:35 gmt
    [connection] => close
)
判断远程文件是否存在代码如下:
复制代码 代码如下:
//判断远程文件是否存在  
function remote_file_exists($url) {  
        $executetime = ini_get('max_execution_time');  
        ini_set('max_execution_time', 0);  
        $headers = @get_headers($url);  
        ini_set('max_execution_time', $executetime);  
        if ($headers) {  
            $head = explode(' ', $headers[0]);  
            if ( !emptyempty($head[1]) && intval($head[1])         }  
        return false;  
}
排除重定向的实例代码如下:
复制代码 代码如下:
/**
 * fetches all the real headers sent by the server in response to a http request without redirects
 * 获取不包含重定向的报头
 */
function get_real_headers($url,$format=0,$follow_redirect=0) { 
  if (!$follow_redirect) { 
    //set new default options 
    $opts = array('http' => 
        array('max_redirects'=>1,'ignore_errors'=>1) 
    ); 
    stream_context_get_default($opts); 
  } 
  //get headers 
    $headers=get_headers($url,$format); 
    //restore default options 
  if (isset($opts)) { 
    $opts = array('http' => 
        array('max_redirects'=>20,'ignore_errors'=>0) 
    );
    stream_context_get_default($opts); 
  } 
  //return 
    return $headers; 

?>
希望本文所述对大家的php程序设计有所帮助。
http://www.bkjia.com/phpjc/919259.htmlwww.bkjia.comtruehttp://www.bkjia.com/phpjc/919259.htmltecharticlephp使用get_headers函数判断远程文件是否存在的方法, 本文实例讲述了php使用get_headers函数判断远程文件是否存在的方法。分享给大家供大家...
其它类似信息

推荐信息