您好想检查一些远程文件大小的文件大小,下面的csize函数在localhost中正常工作。但是当我托管在google app引擎中时,我知道没有curl支持。所以我使用了purl包装器。仍然遇到错误。
我听说有可能在gae php文件中使用java。如果是,那么java中是否有任何函数可以获取远程文件的文件大小?如果是这样,如何在php中使用它。
<?php
require_once 'Purl.php';
echo csize('http://www.example.com');
function csize($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$size = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
return $size;
}
最佳答案
只需使用HTTP Streams API
function csize($url) {
$options = ['http' => [
'method' => 'HEAD',
],
];
$ctx = stream_context_create($options);
$result = file_get_contents($url, false, $ctx);
if ($result !== false) {
foreach($http_response_header as $header) {
if (preg_match("/Content-Length: (\d+)/i", $header, $matches)) {
return $matches[1];
}
}
}
}