以前我有講過程關于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,才能使用
例,代碼如下:
- <?php
- $url = 'http://www.companysz.com';
- print_r(get_headers($url));
- print_r(get_headers($url, 1));
- ?>
- 返回值
- Array
- (
- [0] => HTTP/1.1 200 OK
- [1] => Date: Sat, 29 May 2004 12:28:13 GMT
- [2] => Server: Apache/1.3.27 (Unix) (Red-Hat/Linux)
- [3] => Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT
- [4] => ETag: "3f80f-1b6-3e1cb03b"
- [5] => Accept-Ranges: bytes
- [6] => Content-Length: 438
- [7] => Connection: close
- [8] => Content-Type: text/html
- )
- Array
- (
- [0] => HTTP/1.1 200 OK
- [Date] => Sat, 29 May 2004 12:28:14 GMT
- [Server] => Apache/1.3.27 (Unix) (Red-Hat/Linux)
- [Last-Modified] => Wed, 08 Jan 2003 23:11:55 GMT
- [ETag] => "3f80f-1b6-3e1cb03b"
- [Accept-Ranges] => bytes
- [Content-Length] => 438
- [Connection] => close
- [Content-Type] => text/html
- )
例,代碼如下:
- //判斷遠程文件是否存在
- 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)
- ); //開源軟件:Vevb.com
- stream_context_get_default($opts);
- }
- //return
- return $headers;
- }
- ?>
|
新聞熱點
疑難解答