您的位置:首页 > 编程语言 > PHP开发

php获取远程文件大小的三种方法(实例代码)

2013-07-13 11:03 1166 查看
PHP中获取远程文件大小的三种方法。

1、使用file_get_contents()

<?php
//file_get_contents用法
//by www.jbxue.com
$file = file_get_contents($url);
echo strlen($file);
?>


2. 使用get_headers()

<?php
//get_headers用法
//by www.jbxue.com
$header_array = get_headers($url, true);
$size = $header_array['Content-Length'];
echo $size;
?>


备注:此方法需要打开allow_url_fopen!

如未打开,则会显示:

Warning: get_headers() [function.get-headers]: URL file-access is disabled in the server configuration

3、使用fsockopen()

<?php
//fsockopen用法
//by www.jbxue.com
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;
}
}
?>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: