获取远程文件的大小

时间:2015-01-07 10:02:42

标签: php

我想获得远程文件的大小。它可以通过以下代码完成:

$headers = get_headers("http://addressoffile", 1);
$filesize= $headers["Content-Length"];

但我不直接知道文件地址。但是我有一个重定向到原始文件的地址。

例如:我有地址http://somedomain.com/files/34 当我将此地址放入浏览器的url栏或使用函数file_get_contents('myfile.pdf',"http://somedomain.com/files/34");时,它会开始下载原始文件。

如果我使用上述函数计算文件大小,那么使用地址http://somedomain.com/files/34,它返回大小为0.

有没有办法获取http://somedomain.com/files/34重定向的地址。

或用于计算重定向文件(原始文件)大小的任何其他解决方案。

3 个答案:

答案 0 :(得分:5)

如果你想获得一个远程文件的大小,你需要考虑其他方式。在这篇文章中,我将向您展示如何通过下载文件从头文件信息中获取远程文件的大小。我将向您展示两个例子。一个是使用get_headers函数,另一个是使用cURL。使用get_headers是一种非常简单的方法,适用于每个人。使用cURL更先进,更强大。您可以使用其中任何一个。但我建议使用cURL方法。我们走了......

get_headers方法:

/**
* Get Remote File Size
*
* @param sting $url as remote file URL
* @return int as file size in byte
*/
function remote_file_size($url){
# Get all header information
$data = get_headers($url, true);
# Look up validity
if (isset($data['Content-Length']))
    # Return file size
    return (int) $data['Content-Length'];
}

<强>使用

echo remote_file_size('http://www.google.com/images/srpr/logo4w.png');

cURL方法

/**
* Remote File Size Using cURL
* @param srting $url
* @return int || void
*/
function remotefileSize($url) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
curl_exec($ch);
$filesize = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
curl_close($ch);
if ($filesize) return $filesize;
}

<强>使用

echo remotefileSize('http://www.google.com/images/srpr/logo4w.png');

答案 1 :(得分:3)

如果网站重定向到。您可以使用的位置标题:

// get the redirect url
$headers = get_headers("http://somedomain.com/files/34", 1);
$redirectUrl = $headers['Location'];

// get the filesize
$headers = get_headers($redirectUrl, 1);
$filesize = $headers["Content-Length"];

请注意,此代码不能在生产中使用,因为不检查现有的数组键或错误处理。

答案 2 :(得分:0)

cURL方法很好,因为在某些服务器get_headers被禁用。但如果您的网址有httphttps和...,则需要:

<?php

function remotefileSize($url)
{
    //return byte
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_NOBODY, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
    curl_exec($ch);
    $filesize = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
    curl_close($ch);
    if ($filesize) return $filesize;
}

$url = "https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png";
echo remotefileSize($url);

?>
相关问题