Skip to content
David Kittell
David Kittell

Application & System: Development / Integration / Orchestration

  • Services
    • Application Development
    • Online Application Integration
  • Code
  • Online Tools
  • Tech Support
David Kittell

Application & System: Development / Integration / Orchestration

PHP – Directory File Size – Recursive

Posted on February 23, 2016January 4, 2017 By David Kittell
<?php
$path = '/var/www/html';

function filesize_recursive($path)
	{
		$ret = 0;

		try
		{
			if(!file_exists($path)) return 0;
			if(is_file($path)) return filesize($path);
			
			foreach(glob($path."/*") as $fn)
			$ret += filesize_recursive($fn);
		}
		catch(Exception $e)
		{
			echo 'Message: ' .$e->getMessage();
		}
		return $ret;
	}
 
function display_size($size)
	{
		$sizes = array('B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
		$retstring = '%01.2f %s'; 
		$lastsizestring = end($sizes);
		foreach ($sizes as $sizestring)
			{
				if ($size < 1024) { break;}
				if ($sizestring != $lastsizestring) { $size /= 1024; }
			}
		if ($sizestring == $sizes[0]) { $retstring = '%01d %s'; }
		return sprintf($retstring, $size, $sizestring);
	}
 
echo "Folder {$path} size: ".display_size(filesize_recursive($path))."";
?>
<?PHP
function ByteSize($bytes) 
    {
    $size = $bytes / 1024;
    if($size < 1024)
        {
        $size = number_format($size, 2);
        $size .= ' KB';
        } 
    else 
        {
        if($size / 1024 < 1024) 
            {
            $size = number_format($size / 1024, 2);
            $size .= ' MB';
            } 
        else if ($size / 1024 / 1024 < 1024)  
            {
            $size = number_format($size / 1024 / 1024, 2);
            $size .= ' GB';
            } 
        }
    return $size;
    } 

function recursive_directory_size($directory, $format=FALSE)
{
	$size = 0;
	if(substr($directory,-1) == '/')
	{
		$directory = substr($directory,0,-1);
	}
	if(!file_exists($directory) || !is_dir($directory) || !is_readable($directory))
	{
		return -1;
	}
	if($handle = opendir($directory))
	{
		while(($file = readdir($handle)) !== false)
		{
			$path = $directory.'/'.$file;
			if($file != '.' && $file != '..')
			{
				if(is_file($path))
				{
					$size += filesize($path);
				}elseif(is_dir($path))
				{
					$handlesize = recursive_directory_size($path);
					if($handlesize >= 0)
					{
						$size += $handlesize;
					}else{
						return -1;
					}
				}
			}
		}
		closedir($handle);
	}
	if($format == TRUE)
	{
		if($size / 1048576 > 1)
		{
			return round($size / 1048576, 1).' MB';
		}elseif($size / 1024 > 1)
		{
			return round($size / 1024, 1).' KB';
		}else{
			return round($size, 1).' bytes';
		}
	}else{
		return $size;
	}
}

// Show disk space used by your complete site
echo '<p>'. $_SERVER['DOCUMENT_ROOT'].'/<br>';
$f = $_SERVER['DOCUMENT_ROOT'].'/';
$size =  ByteSize(recursive_directory_size($f));
echo $size;

// Show disk spaced used only in downloads and subdirectories
echo '<p>'. $_SERVER['DOCUMENT_ROOT'].'/downloads/<br>';
$f = $_SERVER['DOCUMENT_ROOT'].'/downloads/';
$size =  ByteSize(recursive_directory_size($f));
echo $size;

?>
Originally Posted on February 23, 2016
Last Updated on January 4, 2017
All information on this site is shared with the intention to help. Before any source code or program is ran on a production (non-development) system it is suggested you test it and fully understand what it is doing not just what it appears it is doing. I accept no responsibility for any damage you may do with this code.

Related

Code PHP

Post navigation

Previous post
Next post

Related Posts

File Extension

Posted on October 17, 2013October 26, 2015

If you are working in a database that has asset/file storage and need to get just the extension of the column this query will help save time. SELECT CASE WHEN filepath LIKE ‘%.%’ THEN RIGHT(filepath, Len(filepath) – Charindex(‘.’, filepath)) ELSE filepath END FilePath FROM tbl1 Originally Posted on October 17,…

Read More

Ektron – User Access List

Posted on August 20, 2014October 26, 2015

Similar to Ektron SQL – List All Users If you simply need a list of all of your CMS users whether they are admin or otherwise this script will help SELECT [user_name] AS ‘Username’, ([first_name] + ‘ ‘ + [last_name]) AS ‘Name’ FROM [user_to_group_tbl] utgt LEFT OUTER JOIN [usergroups] ug…

Read More

UNIX Bash – Get Latest File Name Based On DateTime

Posted on July 7, 2016

Working on a backup and restore script I often need only to know what the latest backup/archive file is, this command helps you learn that. ls -ltr | tail -1 |cut -d’ ‘ -f10 All information on this site is shared with the intention to help. Before any source code…

Read More

Code

Top Posts & Pages

  • PowerShell - Rename Pictures to Image Taken
  • Front Page
  • C# - Start/Stop/Restart Services
  • MacPorts / HomeBrew - Rip CD tracks from terminal
  • PowerShell - Show File Extensions

Recent Posts

  • Javascript – Digital Clock with Style
  • BASH – Web Ping Log
  • BASH – Picture / Video File Name Manipulation
  • Mac OSX Terminal – Create SSH Key
  • Bash – Rename Picture

Top Posts

  • PowerShell - Rename Pictures to Image Taken
  • C# - Start/Stop/Restart Services
  • MacPorts / HomeBrew - Rip CD tracks from terminal
  • PowerShell - Show File Extensions
  • SQLite - Auto-Increment / Auto Generate GUID
©2025 David Kittell | WordPress Theme by SuperbThemes