How to get the file size of a remotely stored image? (php)

ⅰ亾dé卋堺 提交于 2019-11-28 08:56:18

问题


Let's say we have an image file, stored in a remote server (for example, let's take this image), how can we determine (in PHP code) it's file size?

If the file was on server, we would have used filesize (see here), but this wouldn't work on a remote file (see here).

The other alternative is to check for the "Content-Length", but I believe it wouldn't work for an image file (see here)

I would like for a solution like the one given here (e.g, something like:

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

But without the need to download the image. Is that possible?


回答1:


Assuming you're worried about the size of the file (not the dimensions of the image), you can grab Content-Length and it will usually work.

If the server on the other end does't supply the header, you'll have no choice but to GET the file, and check its size locally.

<?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";



回答2:


echo get_headers($url,1)['Content-Length'];




回答3:


Someone else has a function for that that basically does it as a socket connection: http://snippets.dzone.com/posts/show/1207



来源:https://stackoverflow.com/questions/3894653/how-to-get-the-file-size-of-a-remotely-stored-image-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!