Easiest way to grab filesize of remote file in PHP

2019-01-11 18:52发布

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

标签: php http curl
5条回答
在下西门庆
2楼-- · 2019-01-11 19:00

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.

查看更多
叼着烟拽天下
3楼-- · 2019-01-11 19:00

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'];
查看更多
该账号已被封号
4楼-- · 2019-01-11 19:08

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

strlen(file_get_contents($url));
查看更多
男人必须洒脱
5楼-- · 2019-01-11 19:16

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

查看更多
爷的心禁止访问
6楼-- · 2019-01-11 19:17

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 :-(

查看更多
登录 后发表回答