PHP: www-filesize
To get the filesize of a file that isn’t located on your own server is not such
an easy thing! There’s this nice function in PHP to get the size of your files,
filesize() – but it just works for local files.
This workaround should work. – kinda slow, as you need to make a connection to the
remote host, but that’s probably the only way to do it:
sample usage:
1 2 3 | $url = "http://www.your.url/file.zip"; $size = getRemoteSize($url); // filesize in bytes echo (round(abs($size)/1024)).' kb'; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | /** * Gets the filesize of a remotely located file * * @access public * @param string $url URL to file * @return integer filesize in bytes */ function getRemoteSize($url) { $parsedUrl = parse_url($url); $host = $parsedUrl['host']; $path = $parsedUrl['path']; $ourhead = ''; $fp = fsockopen($host, 80, $errno, $errstr, 20); if(!$fp) { exit("$errstr ($errno) \n"); } else { $out = "HEAD $url HTTP/1.1\r\n"; $out .= "HOST: dummy\r\n"; $out .= "Connection: close\r\n\r\n"; fputs($fp,$out); while (!feof($fp)) { $ourhead = sprintf("%s%s", $ourhead, fgets ($fp,128)); } } fclose($fp); $split1 = explode("content-length: ", strtolower($ourhead)); if(!@$split1[1]) exit('Error: No content length'); $split2 = explode("\r\n", $split1[1]); $size = (int) $split2[0]; // size in bytes return $size; } |
I’ve written a full-featured static class which is able to determine the filesize of either a local file, a remote file or the recursive size of a local directory:
Sd_FileSize.class.php
Use getSize() for byte retrieval and getSizeHuman() for human readable size strings.
sample usage:
1 2 3 4 | include_once('Sd_FileSize.class.php'); echo Sd_FileSize::getSizeHuman('file.zip') echo Sd_FileSize::getSizeHuman('directory/test'); echo Sd_FileSize::getSizeHuman('http://www.example.com/file.zip'); |























