Skip to content

Instantly share code, notes, and snippets.

@rendfall
Created October 16, 2016 20:51
Show Gist options
  • Save rendfall/4a1628a450d1b6ce60d78615dc74db1d to your computer and use it in GitHub Desktop.
Save rendfall/4a1628a450d1b6ce60d78615dc74db1d to your computer and use it in GitHub Desktop.
Get remote filesize
function getRemoteFilesize($url, $formatSize = true, $useHead = true) {
if (false !== $useHead) {
stream_context_set_default(array('http' => array('method' => 'HEAD')));
}
$head = array_change_key_case(get_headers($url, 1));
// content-length of download (in bytes), read from Content-Length: field
$clen = isset($head['content-length']) ? $head['content-length'] : 0;
// cannot retrieve file size, return "-1"
if (!$clen) {
return -1;
}
if (!$formatSize) {
return $clen; // return size in bytes
}
$size = $clen;
switch ($clen) {
case $clen < 1024:
$size = $clen .' B'; break;
case $clen < 1048576:
$size = round($clen / 1024, 2) .' KiB'; break;
case $clen < 1073741824:
$size = round($clen / 1048576, 2) . ' MiB'; break;
case $clen < 1099511627776:
$size = round($clen / 1073741824, 2) . ' GiB'; break;
}
return $size; // return formatted size
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment