How to get folder size?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
alirezan1
Forum Newbie
Posts: 1
Joined: Sun Jan 23, 2005 4:33 am

How to get folder size?

Post by alirezan1 »

Hello
I want to write a script that gets the size of a folder. I tried:

disk_total_space( "../~test" ) but it didn't work. it just shows the total space on the disk which is not what I want.
I want to get the information about a folder only.
can somebody help please?

Thanks
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

mcog_esteban
Forum Contributor
Posts: 127
Joined: Tue Dec 30, 2003 3:28 pm

Post by mcog_esteban »

see if this helps:

Code: Select all

<?php

function dir_size($dir)
{
	global $total;
    print(\"\n\");
	
	//check if file,dir exists
	if(file_exists($dir))
	{
    // open directory
    $myDirectory = dir($dir);
	
    // get each entry
	    while(FALSE !== ($entryName = $myDirectory->read()))
	    {
	    	if($entryName != \".\" && $entryName != \"..\") 
	    	{
	    		if(is_dir($dir.$entryName))
	        	{
	        		$dirs[] = $entryName;	
	        	}
	        	else
	        	{	
	        		// get name and file size
	    			$name = $entryName;
	    			$size = filesize($dir.$entryName);
	    			//add file size
	    			$total += $size;
	        	}	
	        	
	        }	
	    }
	    // close directory
 	   $myDirectory->close();

	}
    
    //there's sub dir's ?	
	if(count($dirs) != 0)
	{
		foreach($dirs as $key => $value)
		{
			//do the same for each sub dir	
			dir_size($dir.$value.\"/\");
		}	
	}
}			

$total = 0;
dir_size(\"./\");
echo number_format($total).\" bytes\";
?>
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

beware recursion has the potential to stack overflow, as I noted in the linked thread.
Post Reply