PHP如何判断远程文件是否存在



PHP如何判断远程文件是否存在?

方法1 使用 get_headers() 函数

格式:array get_headers ( string $url [, int $format ] )

get_headers函数: 取得服务器响应一个 HTTP 请求所发送的所有标头,返回一个数组,该数组包含服务器响应一个 HTTP 请求所发送的标头。如果失败则返回 FALSE 并发出一条 E_WARNING 级别的错误信息。

如果将可选的 format 参数设为 1,则 get_headers() 会解析相应的信息并设定数组的键名。

注: 自 PHP 5.1.3 起本函数使用参数,其可以用 stream_context_get_default() 函数设定和修改。

例子:

<?php
$url = ‘http://www.sohu.com’;

print_r(get_headers($url));

print_r(get_headers($url, 1));
?>


上例的输出类似:

Array
(
[0] => HTTP/1.0 200 OK
[1] => Last-Modified: Tue, 14 Jul 2009 12:00:32 GMT
[2] => Content-Type: text/html
[3] => Date: Tue, 14 Jul 2009 12:04:26 GMT
[4] => Server: Apache/1.3.37 (Unix) mod_gzip/1.3.26.1a
[5] => Expires: Tue, 14 Jul 2009 12:05:36 GMT
[6] => Cache-Control: max-age=70
[7] => Vary: Accept-Encoding, Accept-Encoding, Accept-Encoding,X-Up-Calling-Line-id,X-Source-ID,X-Up-Bearer-Type
[8] => Age: 21
[9] => Content-Length: 241249
[10] => X-Cache: HIT from 32583030.43658675.41464475.sohu.com
[11] => Via: 1.1 32583030.43658675.41464475.sohu.com:80 (squid)
[12] => Connection: close
)
Array
(
[0] => HTTP/1.0 200 OK
[Last-Modified] => Tue, 14 Jul 2009 12:00:32 GMT
[Content-Type] => text/html
[Date] => Tue, 14 Jul 2009 12:04:26 GMT
[Server] => Apache/1.3.37 (Unix) mod_gzip/1.3.26.1a
[Expires] => Tue, 14 Jul 2009 12:05:36 GMT
[Cache-Control] => max-age=70
[Vary] => Accept-Encoding, Accept-Encoding, Accept-Encoding,X-Up-Calling-Line-id,X-Source-ID,X-Up-Bearer-Type
[Age] => 21
[Content-Length] => 241249
[X-Cache] => HIT from 32583030.43658675.41464475.sohu.com
[Via] => 1.1 32583030.43658675.41464475.sohu.com:80 (squid)
[Connection] => close
)

 

方法2 :使用自定义函数

<?php
function get_headers_x($url,$format=0, $user=”, $pass=”, $referer=”) {
if (!empty($user)) {
$authentification = base64_encode($user.’:’.$pass);
$authline = “Authorization: Basic $authentification\r\n”;
}

if (!empty($referer)) {
$refererline = “Referer: $referer\r\n”;
}

$url_info=parse_url($url);
$port = isset($url_info['port']) ? $url_info['port'] : 80;
$fp=fsockopen($url_info['host'], $port, $errno, $errstr, 30);
if($fp) {
$head = “GET “.@$url_info['path'].”?”.@$url_info['query'].” HTTP/1.0\r\n”;
if (!empty($url_info['port'])) {
$head .= “Host: “.@$url_info['host'].”:”.$url_info['port'].”\r\n”;
} else {
$head .= “Host: “.@$url_info['host'].”\r\n”;
}
$head .= “Connection: Close\r\n”;
$head .= “Accept: */*\r\n”;
$head .= $refererline;
$head .= $authline;
$head .= “\r\n”;

fputs($fp, $head);
while(!feof($fp) or ($eoheader==true)) {
if($header=fgets($fp, 1024)) {
if ($header == “\r\n”) {
$eoheader = true;
break;
} else {
$header = trim($header);
}

if($format == 1) {
$key = array_shift(explode(‘:’,$header));
if($key == $header) {
$headers[] = $header;
} else {
$headers[$key]=substr($header,strlen($key)+2);
}
unset($key);
} else {
$headers[] = $header;
}
}
}
return $headers;

} else {
return false;
}
}
?>