码迷,mamicode.com
首页 > Web开发 > 详细

PHP获取文件大小的几种方法!

时间:2019-12-21 11:27:06      阅读:104      评论:0      收藏:0      [点我收藏+]

标签:soc   fun   span   获取   iss   fputs   单位   isset   use   

一、get_header($url,true):
$url = http://www.xxx.com/MoJing_win_x86_64_V5.125.zip;
$res = get_headers($url,true);   
  echo "<pre>";
  print_R($res);
  die; 
$filesize = round($res[Content-Length]/1024/1024,2);//四舍五入获取文件大小,单位M

 

技术图片
image.png
二、curl:
$url = http://www.3d414.com/MoJing_win_x86_64_V5.125.zip;
echo getFileSize($url);die;//71741458
function getFileSize($url,$user=‘‘,$pw=‘‘)   
{    
    ob_start();    
    $ch = curl_init($url);    
    curl_setopt($ch, CURLOPT_HEADER, 1);    
    curl_setopt($ch, CURLOPT_NOBODY, 1);    
    if (!empty($user) && !empty($pw))   
    {   
        $headers = array(Authorization: Basic  . base64_encode($user.:.$pw));   
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);   
    }   
    $okay = curl_exec($ch);   
    curl_close($ch);    
    $head = ob_get_contents();    
    ob_end_clean();   
   
    //echo ‘<br>head-->‘.$head.‘<----end <br>‘;   
    
    $regex = /Content-Length:\s([0-9].+?)\s/;   
    $count = preg_match($regex, $head, $matches);    
    $size = isset($matches[1])?$matches[1]:unknown;    
    //$last=round($size/(1024*1024),3);    
    //return $last.‘ MB‘;    
    return $size;   
}  

 

三、fsockopen:
$url = http://www.xxx.com/MoJing_win_x86_64_V5.125.zip;
echo getFileSize($url);die;
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.1\r\n");   
        fputs($fp,"Host:$url[host]\r\n\r\n");   
        while(!feof($fp))   
        {   
            $tmp = fgets($fp);   
            if(trim($tmp) == ‘‘)   
            {   
                break;   
            }   
            elseif(preg_match(/Content-Length:(.*)/si,$tmp,$arr))   
            {   
                return trim($arr[1]);   
            }   
        }   
        return null;   
    }   
    else   
    {   
        return null;   
    }   
}  

 

filesize(),只能获取本地文件大小,不能获取远程文件大小:
$url = ./v3.rar;//  获取本地文件
$url =http://www.xxx.cc/v3.rar;//获取远程文件  
echo filesize($url);

 

file_get_contents(),获取文件内容,strlen()获取内容大小:

 

 

PHP获取文件大小的几种方法!

标签:soc   fun   span   获取   iss   fputs   单位   isset   use   

原文地址:https://www.cnblogs.com/bluealine/p/12076316.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!