【问题标题】:get remote file size (without using Content-Length field)获取远程文件大小(不使用 Content-Length 字段)
【发布时间】:2012-04-11 05:44:09
【问题描述】:

我需要在不下载的情况下获取远程文件的大小。我使用此代码,但某些网站的标题不包含 Content-Length: 字段。在这种情况下如何获取文件大小?

$ch = curl_init("http://wordpress.org/latest.zip");
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$data = curl_exec($ch);
curl_close($ch);

$contentLength = 'unknown';
if (preg_match('/Content-Length: (\d+)/', $data, $matches)) {
  $contentLength = (int)$matches[1];
}
echo $contentLength;

这是 echo $data 的结果;

HTTP/1.1 200 OK
Server: nginx
Date: Tue, 10 Apr 2012 11:32:20 GMT
Content-Type: application/zip
Connection: close
Pragma: no-cache
Cache-control: private
Content-Description: File Transfer
Content-Disposition: attachment; filename=wordpress-3.3.1.zip
Content-MD5: d6332c76ec09fdc13db412ca0b024df9
X-nc: EXPIRED luv 139

【问题讨论】:

  • 会不会是返回了头部,但是名字是小写的'content-length'?或者冒号和实际值之间有空格。
  • echo $data 查看内容和标题
  • @safarov,我将 echo $data 的结果添加到问题中。
  • @artaskerov - 这可能有用:perlmonks.org/?node_id=641741

标签: php curl


【解决方案1】:

如果 Content-Length 标头不存在,则表示文件大小未知。在您的情况下,您有 Content-Disposition 标头,这意味着可下载文件是服务器响应的附件(与电子邮件附件相同)。因此,如果您没有 Content-Length 标头,则无法获取大小。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-05
    • 2012-07-03
    • 2023-03-28
    • 2015-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    相关资源
    最近更新 更多