如何使用cURL从googlecode获取远程文件的文件大小? [英] How to get a file size of remote file from googlecode with cURL?

查看:161
本文介绍了如何使用cURL从googlecode获取远程文件的文件大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用cURL来获取远程文件 compiler-latest.zip(googlecode.com)的文件大小,而无需实际下载它,这是我的PHP代码:

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

但是,我的文件大小(1379字节)为 HTTP / 1.1 404未找到状态错误404文档的内容。
因此,如果我设置(CURLOPT_NOBODY,0),它将下载文件并返回其正确的文件大小(当前为3820320字节)。我的问题是如何在不下载的情况下获取正确大小的 compiler-latest.zip文件?

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?

重要提示:此代码可与外部任何其他url正常工作

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

推荐答案

使用 get_headers 函数:

<?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;

这篇关于如何使用cURL从googlecode获取远程文件的文件大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆