Search code examples
phpfilesizestat

PHP function stat(): stat failed for remote image


There are many similar questions to this, but all involve performing stat() or filesize() on local files, which don't work because you need the full path.

This problem is different, since I have a handful of remote images that have the full paths and I am still unable to retrieve the size of them. Here is an example:

stat("https://cdn-img.health.com/sites/default/files/1532113674/1-opener-sleep-a-z-GettyImages-485559412.jpg");

This throws an error saying "stat failed". I'm also unable to get the image size from the filesize() function, retrieving the "Content-Length" or "X-Original-Content-Length" headers (which aren't passed), or curling the image and retrieving the CURLINFO_CONTENT_LENGTH_DOWNLOAD field. Similarly, in Ruby, I am unable to get the size of this image with the traditional methods with the exception of the Mechanize library, which just works. Here are the headers to the image in the example:

HTTP/1.1 200 OK
Content-Type:   image/jpeg
Transfer-Encoding:  chunked
Connection: keep-alive
Cache-Control:  max-age=1800
Date:   Fri, 03 Aug 2018 14:08:39 GMT
ETag:   "90c755-5717304f98380-gzip"
Expires:    Fri, 03 Aug 2018 14:38:39 GMT
Last-Modified:  Fri, 20 Jul 2018 19:08:22 GMT
P3P:    CP='PHY ONL UNI PUR FIN COM NAV INT DEM CNT STA PRE CUR ADMa DEVa TAIo PSAo PSDo IVAo IVDo CONo TELo OTPi OUR UNRo PUBi OTRo IND DSP CAO COR'
Server: Apache
TI-Varnish-Age: 0
Via:    1.1 varnish, 1.1 ba150248cd293ea895c35304503c9f27.cloudfront.net (CloudFront)
X-Varnish:  1920400558
Vary:   Accept-Encoding
Age:    19
X-Cache:    Hit from cloudfront
X-Amz-Cf-Id:    pKXUfsB5egUfk4Te7oxIG7TgFLoUfMSUWqGZxd5822_ejvorITbFsg==

Any suggestions?


Solution

  • You can get the size by doing:

    strlen(file_get_contents('http://link.of/image.jpg'));
    

    As long as you have allow_url_fopen enabled it will work. Otherwise you will need to use cURL.