据我了解您的问题:您想获取由 URL 给出的远程字段的文件大小,但您不确定哪种解决方案最好/最快。
首先,CURL、file_get_contents() 和 fread() 在这种情况下最大的区别是 CURL 和 file_get_contents() 将整个内容放入内存,而 fopen() 让您可以更好地控制哪些部分您要阅读的文件。我认为 fopen() 和 file_get_contents() 在您的情况下几乎是等效的,因为您正在处理小文件并且您实际上想要获取整个文件。所以它在内存使用方面没有任何区别。
CURL 只是 file_get_contents() 的老大哥。它实际上是一个完整的 HTTP-Client,而不是某种简单功能的包装器。
关于 HTTP:不要忘记 HTTP 不仅仅是 GET 和 POST。你为什么不直接使用资源的元数据来检查它的大小在你甚至得到它?这是 HTTP 方法 HEAD 的用途之一。 PHP 甚至带有一个用于获取标题的内置函数:get_headers()。但是它有一些缺陷:它仍然发送一个 GET 请求,这可能会慢一点,并且它遵循重定向,这可能会导致安全问题。但是你可以通过调整默认上下文很容易地解决这个问题:
$opts = array(
'http' =>
array(
'method' => 'HEAD',
'max_redirects'=> 1,
'ignore_errors'=> true
)
);
stream_context_set_default($opts);
完成。现在您可以简单地获取标题:
$headers = get_headers('http://example.com/pic.png', 1);
//set the keys to lowercase so we don't have to deal with lower- and upper case
$lowerCaseHeaders = array_change_key_case($headers);
// 'content-length' is the header we're interested in:
$filesize = $lowerCaseHeaders['content-length'];
注意:filesize() 将不在 http / https 流包装器上工作,因为不支持 stat() (http://php.net/manual/en/wrappers.http.php)。
差不多就是这样。当然,如果您更喜欢它,您也可以achieve the same with CURL 一样简单。该方法将是相同的(红色标题)。
以下是使用 CURL 获取文件及其大小(下载后)的方法:
// Create a CURL handle
$ch = curl_init();
// Set all the options on this handle
// find a full list on
// http://au2.php.net/manual/en/curl.constants.php
// http://us2.php.net/manual/en/function.curl-setopt.php (for actual usage)
curl_setopt($ch, CURLOPT_URL, 'http://example.com/pic.png');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Send the request and store what is returned to a variable
// This actually contains the raw image data now, you could
// pass it to e.g. file_put_contents();
$data = curl_exec($ch);
// get the required info about the request
// find a full list on
// http://us2.php.net/manual/en/function.curl-getinfo.php
$filesize = curl_getinfo($ch, CURLINFO_SIZE_DOWNLOAD);
// close the handle after you're done
curl_close($ch);
纯 PHP 方法:http://codepad.viper-7.com/p8mlOt
使用 CURL:http://codepad.viper-7.com/uWmsYB
对于文件大小的格式良好且人类可读的输出,我从 Laravel 学到了这个惊人的功能:
function get_file_size($size)
{
$units = array('Bytes', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB');
return @round($size / pow(1024, ($i = floor(log($size, 1024)))), 2).' '.$units[$i];
}
如果您不想处理所有这些问题,请查看Guzzle。对于任何类型的 HTTP 内容,它都是一个非常强大且非常易于使用的库。