How to get the file size of a remote saved image? (PHP)

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

If the file was on the server, we would use filesize ( see here ), but this would not work in the remote file ( see here ).

Another option is to check the "Content-Length", but I believe that it will not work for the image file ( see here )

I would like to get a solution like the one listed here (for example, 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 upload an image. Is it possible?

+3
source share
3 answers

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

If the server from the other end does not give a header, you will have no choice but to get the GET 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";
+8
source

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

+1
source

Source: https://habr.com/ru/post/1768702/


All Articles