0

実際にダウンロードせずに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);

しかし、このエラー404ドキュメントのファイルサイズ(1379バイト)で「HTTP /1.1404NotFound」ステータスが表示されます。したがって、(CURLOPT_NOBODY、0)を設定すると、ファイルがダウンロードされ、正しいファイルサイズ(現在は3820320バイト)が返されます。私の質問は、「compiler-latest.zip」ファイルをダウンロードせずに正しいファイルサイズを取得する方法です。

重要:このコードは、googlecode.com以外の他のURLでも期待どおりに機能します。

4

2 に答える 2

2

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;
于 2009-12-14T21:39:59.713 に答える
1

また、コンテンツの長さが不足している場合にファイルサイズを取得するにはどうすればよいですか?

于 2010-03-18T11:02:22.350 に答える