Easiest way to grab filesize of remote file in PHP?

Yes. Since the file is remote, you're completely dependent on the value of the Content-Length header (unless you want to download the whole file). You'll want to curl_setopt($ch, CURLOPT_NOBODY, true) and curl_setopt($ch, CURLOPT_HEADER, true).


The best solution which follows the KISS principle

$head = array_change_key_case(get_headers("http://example.com/file.ext", 1));
$filesize = $head['content-length'];

I'm guessing using curl to send a HEAD request is a nice possibility ; something like this would probably do :

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://sstatic.net/so/img/logo.png');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$size = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
var_dump($size);

And will get you :

float 3438

This way, you are using a HEAD request, and not downloading the whole file -- still, you depend on the remote server send a correct Content-length header.


Another option you might think about would be to use filesize... But this will fail : the documentation states (quoting) :

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to List of Supported Protocols/Wrappers for a listing of which wrappers support stat() family of functionality.

And, unfortunately, with HTTP and HTTPS wrappers, stat() is not supported...

If you try, you'll get an error, like this :

Warning: filesize() [function.filesize]: stat failed 
    for http://sstatic.net/so/img/logo.png

Too bad :-(

Tags:

Php

Http

Curl