【问题标题】:How to get a file size of remote file from googlecode with cURL?如何使用 cURL 从 googlecode 获取远程文件的文件大小?
【发布时间】:2009-12-14 17:10:22
【问题描述】:

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

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

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

重要提示:此代码可与 googlecode.com 之外的任何其他网址一起正常工作。

【问题讨论】:

  • 你有没有使用 HEAD 方法来查看 headerS 中是否返回了有用的信息?
  • 是的,我只抓了一个 HEADER,它通常包含所有必要的数据,但在这种特殊情况下不包含。

标签: php curl filesize


【解决方案1】:

使用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;

【讨论】:

  • 谢谢,我的脚本已经使用了这个函数,更简单的方法:$data = get_headers($url, 1); echo $data['Content-Length'];我只是好奇如何用 CURL 完成它,就是这样。
【解决方案2】:

当内容长度丢失时如何获取文件大小?

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2023-03-04
  • 2023-03-28
  • 2015-03-05
  • 2021-09-11
  • 1970-01-01
  • 1970-01-01
  • 2011-05-28
  • 2019-04-27
相关资源
最近更新 更多