Question

I was thinking of doing a head request with cURL, was wondering if this is the way to go?

Was it helpful?

Solution

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).

OTHER TIPS

The best solution which follows the KISS principle

$head = array_change_key_case(get_headers("http://example.com/file.ext", TRUE));
$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 :-(

Using a HEAD request and checking for Content-Length is the standard way to do it, but you can't rely on it in general, since the server might not support it. The Content-Length header is optional, and further the server might not even implement the HEAD method. If you know which server you're probing, then you can test if it works, but as a general solution it isn't bullet proof.

If you don't need a bulletproof solution you can just do:

strlen(file_get_contents($url));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top