使用PHP取远程文件的大小的3种方法

1、【最傻最天真的方法】
将文件使用file_get_contents取回后,strlen
或者存为文件后使用filesize 嘿嘿
[php]
<?PHP
echo strlen(file_get_contents("http://www.4wei.cn"));
?>
[/php]

2、【使用get_headers】
如果没有打开allow_url_fopen
会显示waring
Warning: get_headers() [function.get-headers]: URL file-access is disabled in the server configuration
示例代码如下:

[php]
<?PHP
$a_array = get_headers($url, true);
$size = $a_array[‘Content-Length’];
Echo $size;
?>
[/php]

3、【使用fsockopen,然后正则匹配出文件大小】
使用fsockopen向目标地址发送http request,然后根据服务器的response使用正则匹配
[php]
<?PHP
function get_file_size($url) {
$url = parse_url($url);

if (empty($url[‘host’])) {
return false;
}

$url[‘port’] = empty($url[‘post’]) ? 80 : $url[‘post’];
$url[‘path’] = empty($url[‘path’]) ? ‘/’ : $url[‘path’];

$fp = fsockopen($url[‘host’], $url[‘port’], $error);

if($fp) {
fputs($fp, "GET " . $url[‘path’] . " HTTP/1.1\r\n");
fputs($fp, "Host:" . $url[‘host’]. "\r\n\r\n");

while (!feof($fp)) {
$str = fgets($fp);
if (trim($str) == ”) {
break;
}elseif(preg_match(‘/Content-Length:(.*)/si’, $str, $arr)) {
return trim($arr[1]);
}
}
fclose ( $fp);
return false;
}else {
return false;
}
}

?>
[/php]

发表评论

评论列表(1)