先来简单了解get_headers()函数
get_headers() 返回一个数组,包含有服务器响应一个 HTTP 请求所发送的标头。
get_headers:发送服务器响应HTTP请求
get_headers(字符串url[链接格式])
get_headers()以数组的形式返回服务器HTTP请求。如果执行失败,将返回FALSE和一个错误的水平E_WARNING》。
可选参数设置为1,get_headers()能分析系统的响应速度和集数组中的键。
注意:使用该函数需要把 php.ini里面的allow_url_fopen = On,才能使用
例
代码如下 | 复制代码 |
<?php $url = 'http://www.example.com'; print_r(get_headers($url)); print_r(get_headers($url, 1)); 返回值 Array Array |
例
代码如下 | 复制代码 |
//判断远程文件是否存在 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]) < 400) return true; } return false; } |
例2
排除重定向的例子:
代码如下 | 复制代码 |
<?php /** * 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; } |