James
James

Reputation: 43627

How can I the size of an image file from the URL?

Images and script are hosted on the same account (one site), but we know only the URL of the image.

$image = "http://example.com/images/full-1091.jpg"

How can we get the size of this file?

Pseudo-code:

{ do something with $image and get $image_size }
echo $image_size;

I would prefer $image_size to be formatted in human-readable file sizes, like "156,8 Kbytes" or "20,1 Mbytes".

Upvotes: 9

Views: 26457

Answers (5)

Mahdi Jazini
Mahdi Jazini

Reputation: 791

Please Note:

The result of filesize() function are cached! Use clearstatcache() to clear the cache...

source: http://www.w3schools.com/php/func_filesystem_filesize.asp

Upvotes: 3

Ankur Mukherjee
Ankur Mukherjee

Reputation: 3867

<?php
  $contents=file_get_contents("http://site.com/images/full-1091.jpg");
   // var_dump($contents);
//  $fp =fopen("1.jpeg","w");
  file_put_contents("1.jpeg",$contents);
  $size= filesize("1.jpeg");
  echo $size."in Bytes";
  ?>

Check this it can work for you

Upvotes: -4

Your Common Sense
Your Common Sense

Reputation: 157839

 echo filesize($_SERVER['DOCUMENT_ROOT']."/images/full-1091.jpg");

note that http://site.com/images/full-1091.jpg is not a file

as for the formatted output ("156,8 Kbytes" or "20,1 Mbytes") try to help yourself and use search. There is a ton of answers to this question already.

Upvotes: 0

Sarfraz
Sarfraz

Reputation: 382656

Use filesize function like this:

echo filesize($filename) . ' bytes';

You can also format the unit of the size with this function:

function format_size($size) {
      $sizes = array(" Bytes", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB");
      if ($size == 0) { return('n/a'); } else {
      return (round($size/pow(1024, ($i = floor(log($size, 1024)))), 2) . $sizes[$i]); }
}

Upvotes: 30

Pekka
Pekka

Reputation: 449395

Images and script hosted on the same account (one site).

Then don't use a URL: Use the direct file path and filesize().

Upvotes: 3

Related Questions