2

我正在查看 fsockopen 和诸如此类的 PHP 文档,他们说你不能在远程文件上使用 filesize() 而不用 ftell 或其他东西做一些疯狂的事情(不确定他们到底说了什么),但我有一个很好的想法怎么做:

$file = file_get_contents("http://www.google.com");
$filesize = mb_strlen($file) / 1000; //KBs, mb_* in case file contains unicode

这会是一个好方法吗?当时它看起来非常简单和好用,只是想知道这是否会遇到问题或不是真正的文件大小。

我只希望在文本(网站)上使用它,而不是二进制。

4

3 回答 3

5

这个答案需要 PHP5 和 cUrl。它首先检查标题。如果没有指定 Content-Length,它会使用 cUrl 下载它并检查大小(文件不会保存在任何地方——只是暂时保存在内存中)。

<?php
echo get_remote_size("http://www.google.com/");

function get_remote_size($url) {
    $headers = get_headers($url, 1);
    if (isset($headers['Content-Length'])) return $headers['Content-Length'];
    if (isset($headers['Content-length'])) return $headers['Content-length'];

    $c = curl_init();
    curl_setopt_array($c, array(
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => array('User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3'),
        ));
    curl_exec($c);
    return curl_getinfo($c, CURLINFO_SIZE_DOWNLOAD);
}
?>
于 2010-07-15T03:54:10.507 回答
3

You should look at the get_headers() function. It will return a hash of HTTP headers from an HTTP request. The Content-length header may be a better judge of the size of the actual content, if it's present.

That being said, you really should use either curl or streams to do a HEAD request instead of a GET. Content-length should be present, which saves you the transfer. It will be both faster and more accurate.

于 2010-07-15T02:08:28.280 回答
0

它将获取整个文件,然后从检索到的数据中计算文件大小(而不是字符串长度)。通常文件大小可以直接从文件系统告诉文件大小,而无需先读取整个文件。

所以这会相当慢,并且每次都会在能够检索文件大小之前获取整个文件(字符串长度

于 2010-07-15T01:42:17.617 回答