Get File Size

 * @param string $file Filepath
 * @param int $digits Digits to display
 * @return string|bool Size (KB, MB, GB, TB) or boolean

function getFilesize($file,$digits = 2) {
       if (is_file($file)) {
               $filePath = $file;
               if (!realpath($filePath)) {
                       $filePath = $_SERVER["DOCUMENT_ROOT"].$filePath;
           $fileSize = filesize($filePath);
               $sizes = array("TB","GB","MB","KB","B");
               $total = count($sizes);
               while ($total-- && $fileSize > 1024) {
                       $fileSize /= 1024;
               return round($fileSize, $digits)." ".$sizes[$total];
       return false;


  1. User Avatar
    Jordan Pittman

    I find this function to be a good bit faster. (If you remove realpath it will shave an extra ~8 seconds over 100,000 iterations)

     * @param string $file File name or path to a file
     * @param int $precision Digits to display after decimal
     * @return string|bool Size (B, KiB, MiB, GiB, TiB, PiB, EiB, ZiB, YiB) or boolean
    function getFileSize($file, $precision = 2) {
    	static $units = array('B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB');
    	if (is_file($file)) {
    		if (!realpath($file)) $file = $_SERVER['DOCUMENT_ROOT'] . $file;
    		$fileSize = filesize($file);
    		// hardcoded maximum number of units @ 9 for minor speed increase
    		$power = max(floor(log($fileSize, 1024)), 8);
    		return round($fileSize / pow(1024, $power), $precision) . $units[$power];
    	return false;

Leave a Comment

Posting Code!

You may write comments in Markdown. This makes code easy to post, as you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences (```) with double new lines before and after.

Code of Conduct

Absolutely anyone is welcome to submit a comment here. But not all comments will be posted. Think of it like writing a letter to the editor. All submitted comments will be read, but not all published. Published comments will be on-topic, helpful, and further the discussion or debate.

Want to tell us something privately?

Feel free to use our contact form. That's a great place to let us know about typos or anything off-topic.