Can’t get filesize when reading file over HTTP wrapper
I was trying to get filesize of remote file, accessible via HTTP, using PHP’s wrappers. My attempt to do this has failed. I had all the configuration and settings correct, but still, I wasn’t able to read remote file size.
It turned out, that this is by design in PHP and there isn’t much you can do about this.
To be 100% sure, let me state, that:
- file exists,
httpon the list and
resource(119) of type (stream).
Which all means, that remote file is accessible. And yet, I’m getting:
file_exists($filename): bool(false) is_file($filename): bool(false) is_writable($filename): bool(false) is_readable($filename): bool(false)
And the attempt of calling
filesize($filename) ends with
filesize(): stat failed for... error.
The original Stack Overflow question is here.
The answer can be found in PHP’s docs for HTTP/HTTPS protocol wrappers. The “Options” section explains, that though this protocol allows reading, it does not support
fopen() works like a charm, while
filesize() and other functions, that require
stat() to work, fails for this wrapper. Notice, that PHP documentations says, that these functions supports only some URL wrappers:
As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.
Seems, that HTTP/HTTPS wrapper is not among them.
You may try to use
fopen(), which works with this wrapper, to implement very own version of file size determining function. But, since
fopen() actually opens file (while
filesize() reads file size from the file system / meta data), this would be a really overkill in any scenario, I can think of.
The original answer is here.