PHP 获取远程文件大小的3种解决方法

1、使用file_get_contents()    ----简单常用

<?php
$file = file_get_contents($url);
echo strlen($file);
?>

2. 使用get_headers()

<?php
$header_array = get_headers($url, true);
$size = $header_array['Content-Length'];
echo $size;
?>

PS:
需要打开allow_url_fopen!!!              allow_url_fopen=ON保存在php.ini
如未打开会显示

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

3.使用fsockopen()<?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;
     }
 }
echo get_file_size("//www.jb51.net/images/logo.gif");
?>

 附:

文件大小单位转换问题

<?php
    $type = array("byte", "KB", "MB", "GB");//定义单位数组 
    $size = 1048576;//原始值,单位为byte,1024*1024=1048576
    $i=0;//选用第几个单位
while($size >= 1024)//当当前值大于等于1024时,即转换到下一位,如此循环。当然也可设置为1000,或者更低
{
    $size = $size/1024;//当前值除以1024
    $i++;//所选取的单位增加一个
} 
    $newsize = $size.$type[$i];//最终结果为最终值加上单位
    echo $newsize;       //  1MB
?>

 

posted @ 2019-09-20 17:13  李若盛开  阅读(540)  评论(0)    收藏  举报