通过url获取图片、视频、json、html文件的大小
使用fsockopen() - 已尝试
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;
}else if(preg_match('/Content-Length:(.*)/si',$tmp,$arr)){
return trim($arr[1]);
}
}
return null;
}else{
return null;
}
}
注意,返回的是字节,如果需要转化:
kb:ceil($size / 1024)
m: ceil($size / 1024 / 1024)
以下是同样的方法,另一种封装:
<?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;
}
}
?>
使用file_get_contents()
$file = file_get_contents($url);
echo strlen($file);
使用get_headers()
<?php
$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
使用curl 来获取远程文件大小
// 获取远程文件大小函数
function remote_filesize($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);
}
$ok = curl_exec($ch);
curl_close($ch);
$head = ob_get_contents();
ob_end_clean();
$regex = '/Content-Length:\s([0-9].+?)\s/';
$count = preg_match($regex, $head, $matches);
return isset($matches[1]) ? $matches[1] . " 字节" : "unknown";
}
实例测试
// 实例测试
echo remote_filesize("https://634174214.gitee.io/myblog-www-assets/img/blog-logo.png");
返回的结果是字节