获取远程文件的大小

Get size of a remote file

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

$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 它 return 大小 0。

有什么方法可以获取 http://somedomain.com/files/34 重定向的地址。

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

如果网站重定向通过。位置 header 您可以使用:

// 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"];

请注意,此代码不应用于生产,因为不检查现有数组键或错误处理。

如果您想获得远程文件的大小,您需要考虑其他方式。在此 post 中,我将向您展示如何在不下载文件的情况下从 header 信息中获取远程文件的大小。我将向您展示两个示例。一种是使用 get_headers 函数,另一种是使用 cURL。使用 get_headers 是一种非常简单的方法,适用于每个 body。使用 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');

cURL 方法很好,因为在某些服务器中 get_headers 被禁用。但是如果你的 url 有 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);

?>