如何获取远程存储图像的文件大小?(PHP)

Tal*_*ili 3 php filesize content-length

假设我们有一个存储在远程服务器中的图像文件(例如,让我们拍摄这张图片),我们如何确定(在PHP代码中)它的文件大小?

如果文件在服务器上,我们将使用filesize(参见此处),但这不适用于远程文件(请参阅此处).

另一种方法是检查"内容长度",但我相信它对图像文件不起作用(见这里)

我想要一个像这里给出的解决方案(例如,像:

<?php
function get_remote_size($url) {  // magic
}
echo get_remote_size("http://humus101.com/wp-content/uploads/2009/11/Hummus-soup.jpg");
?>
Run Code Online (Sandbox Code Playgroud)

但无需下载图像.那可能吗?

tim*_*dev 8

假设您担心文件的大小(而不是图像的尺寸),您可以获取内容长度,它通常会起作用.

如果另一端的服务器没有提供标头,你将别无选择,只能获取文件,并在本地检查其大小.

<?PHP
$headers = get_headers('http://humus101.com/wp-content/uploads/2009/11/Hummus-soup.jpg');
$size = null;
foreach($headers as $h){
    /** look for Content-Length, and stick it in $size **/
}
if ($size === null){ //we didn't get a Content-Length header
    /** Grab file to local disk and use filesize() to set $size **/
}

echo "image is $size bytes";
Run Code Online (Sandbox Code Playgroud)