7

I am trying to get a file size of an image from a remote url, I am trying to this like so:

$remoteUrl = $file->guid;
//remote url example: http://myApp/wp-content/uploads/2017/05/Screen-Shot-2017-05-08-at-10.35.54.png  

$fileSize = filesize($remoteUrl);

But, I get:

filesize(): stat failed for http://myApp/wp-content/uploads/2017/05/Screen-Shot-2017-05-08-at-10.35.54.png

Leff
  • 1,968
  • 24
  • 97
  • 201
  • HTTP is not a file system. You'd need to download the content from that URL (with something like CURL) and examine the size of that downloaded content. – David Jun 21 '17 at 11:59
  • 2
    Possible duplicate of [Get size of a remote file](https://stackoverflow.com/questions/27816849/get-size-of-a-remote-file) – alanlittle Jun 21 '17 at 12:02
  • 1
    See [this thread](https://stackoverflow.com/questions/2602612/php-remote-file-size-without-downloading-file) It suggests curl for this task. – Marcelo Staudt Jun 21 '17 at 12:04

3 Answers3

16

You can use HTTP headers to find the size of the object. The PHP function get_headers() can get them:

$headers = get_headers('http://myApp/wp-content/uploads/2017/05/Screen-Shot-2017-05-08-at-10.35.54.png', true);
echo $headers['Content-Length'];

This way you can avoid downloading the entire file. You also have access to all other headers, such as $headers['Content-Type'], which can come in handy if you are dealing with images (documentation).

Quentin Skousen
  • 1,035
  • 1
  • 18
  • 30
Asur
  • 3,727
  • 1
  • 26
  • 34
  • Are you sure, We can get `Content-Length` from each file? – Pooja Jadav May 22 '19 at 04:42
  • @PoojaJadav Acording to [wikipedia](https://en.wikipedia.org/wiki/List_of_HTTP_header_fields) it has a permantent status, so you should expect this header on every response. – Asur May 22 '19 at 08:19
0

That error usually means the supplied URL does not return a valid image. When I try to visit http://myapp/wp-content/uploads/2017/05/Screen-Shot-2017-05-08-at-10.35.54.png it does not show an image in my browser. Double check that the returned URL from $file->guid; is correct.

WizardCoder
  • 3,353
  • 9
  • 20
0

You will need to try a different method, the http:// stream wrapper does not support stat() which is needed for the filesize() function.

This question has some options you might use, using curl to make a HEAD request and inspect the Content-Length header.