PHP: Remote Filesize

19 08 2008

Da die PHP-Funktion ‘filesize’ nur Datei handeln kann, die lokal auf dem Server liegen, kann man die Dateigröße von entfernten Dateien (Remote, Resource) mithilfe folgender Funktionen herausfinden.

PHP4:
function extern_filesize($url)
{
ob_start();
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_exec($ch);
curl_close($ch);

$head = ob_get_contents();
ob_end_clean();

$regex = ‘/Content-Length:\s([0-9].+?)\s/’;
$count = preg_match($regex, $head, $matches);

if (isset($matches[1]))
{
$size = $matches[1];
}
else
{
$size = ‘unbekannt’;
}
return $fsize;
}

Und in PHP5:

function urlfilesize($url,$thereturn) {
if (
substr($url,0,4)==‘http’) {
$x = array_change_key_case(get_headers($url, 1),CASE_LOWER);
$x = $x['content-length'];
}
else {
$x = @filesize($url); }
if (!
$thereturn) { return $x ; }
elseif(
$thereturn == ‘mb’) { return round($x / (1024*1024),2) ; }
elseif(
$thereturn == ‘kb’) { return round($x / (1024),2) ; }
}

echo urlfilesize(‘http://www.file.de/file.csv’,‘mb’)
Quelle: http://de2.php.net/manual/en/function.filesize.php#81906