How to get a file size of remote file from googlecode with cURL?

荒凉一梦 提交于 2019-12-25 16:48:18

问题


I am trying to get a file size of remote file "compiler-latest.zip" (googlecode.com) using cURL without actually downloading it, here is my PHP code:

$url = 'http://closure-compiler.googlecode.com/files/compiler-latest.zip';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // optional
curl_setopt($ch, CURLOPT_MAXREDIRS, 10); // optional
curl_setopt($ch, CURLOPT_TIMEOUT, 60); // optional
$result = curl_exec($ch);
$filesize = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
curl_close($ch);
print 'Filesize: ' . $filesize . '<br><br>';
print_r($result);

But, I get "HTTP/1.1 404 Not Found" status with a file size (1379 bytes) of this error 404 document. So, if I set (CURLOPT_NOBODY, 0) it downloads file and returns its correct file size (currently 3820320 bytes). My question is how to get a correct file size of "compiler-latest.zip" file without downloading it?

IMPORTANT: this code works as expected with any other url outside of googlecode.com.


回答1:


Use get_headers function:

<?php

$headers = get_headers('http://closure-compiler.googlecode.com/files/compiler-latest.zip');

$content_length = -1;

foreach ($headers as $h)
{
    preg_match('/Content-Length: (\d+)/', $h, $m);
    if (isset($m[1]))
    {
        $content_length = (int)$m[1];
        break;
    }
}

echo $content_length;



回答2:


And how to get a file size, when content-length missing?



来源:https://stackoverflow.com/questions/1902187/how-to-get-a-file-size-of-remote-file-from-googlecode-with-curl

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!