background image

PHP 获取远程文件大小常用方法总结

php 有很多方法可以获取远程文件大小的哦,最常用的就有 fsockopen、file_get_contents、curl
函数哦,下面我来给各位总结一下。
1、fsockopen
代码如下
<?php
function getFileSize($url){
$url = parse_url($url);
if($fp = @fsockopen($url['host'],empty($url['port'])?80:$url['port'],$error)){
fputs($fp,"GET ".(empty($url['path'])?'/':$url['path'])." HTTP/1.1rn");
fputs($fp,"Host:$url[host]rnrn");
while(!feof($fp)){
$tmp = fgets($fp);
if(trim($tmp) == ''){
break;
}else if(preg_match('/Content-Length:(.*)/si',$tmp,$arr)){
return trim($arr[1]);
}
}
return null;
}else{
return null;
}
}
//调用方法
echo getFileSize("http://www.111cn.netnet/")
?>
2、使用 file_get_contents()
 代码如下
<?php
$file = file_get_contents($url);
echo strlen($file);
?>
3. 使用 get_headers()
代码如下
<?php
$header_array = get_headers($url, true);
//返回结果
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)