我想获取远程文件的大小。这可以通过以下代码完成:
$headers = get_headers("http://addressoffile", 1);
$filesize= $headers["Content-Length"];
但我不直接知道文件地址。但是我有一个重定向到原始文件的地址。
例如:我有地址http://somedomain.com/files/34
当我将此地址放入浏览器的网址栏中或使用功能file_get_contents('myfile.pdf',"http://somedomain.com/files/34");
时,它开始下载原始文件。
如果我使用上述函数来计算文件大小,那么使用地址http://somedomain.com/files/34
它返回大小 0。
有没有办法获取http://somedomain.com/files/34
重定向的地址。
或任何其他用于计算重定向文件(原始文件)大小的解决方案。
如果你想得到一个远程文件的大小,你需要考虑一些其他方式。在这篇文章中,我将向您展示我们如何在不下载文件的情况下从其标头信息中获取远程文件的大小。我给你们举两个例子。一个使用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');
如果网站通过以下方式重定向。 位置标头 您可以使用:
// 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"];
请注意,此代码不应在生产中使用,因为没有检查现有数组键或错误处理。
cURL方法是好的,因为在某些服务器中get_headers
是禁用的。但是如果你的网址有 http
、 https
和 ...,你需要这个:
<?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);
?>