jump to navigation

Useful Recursive PHP Filesystem Functions January 12, 2012

Posted by Tournas Dimitrios in PHP.
trackback

Could you imagine a web-development language that is entirely isolated from it’s underlying file and operating system ? Fortunately , PHP has a build-in  tool-set  which can be used by developers not only for creating – deleting files and directories   but also executing programs at the shell level .  This article will present three functions that can be used for retrieving information of a given file-system-path or even delete it’s content . I have to emphasize that the code is not written by me , so all applause goes to the owner of these code snippets (at the end of this article is a link to the website that published these functions ) .

Recursively delete whole directories with this function:

This PHP function scans a given directory and will  empty or deletes all files and subdirectories it finds and has permission to delete (not open files , Linux CHMOD) . PHP can easily delete any empty directory with build-in function rmdir() , but it can’t delete any directory which contains some file within it . For that , you need to first delete (unlink )the files inside the directory . If you unlink a file , you are effectively causing the system to forget about it or delete it! The below function exactly does the same , it recursively delete any internal files/directories . Take a look at the code –

function recursive_remove_directory($directory, $empty=FALSE) {
// if the path has a slash at the end we remove it here
if(substr($directory,-1) == '/') {
$directory = substr($directory,0,-1);
	}
// if the path is not valid or is not a directory ...
if(!file_exists($directory) || !is_dir($directory)) {
// ... we return false and exit the function
return FALSE;
// ... if the path is not readable
	}elseif(!is_readable($directory)) {
// ... we return false and exit the function
return FALSE;
// ... else if the path is readable
	}else{
// we open the directory
$handle = opendir($directory);

// and scan through the items inside
while (FALSE !== ($item = readdir($handle))) {
// if the filepointer is not the current directory
// or the parent directory
if($item != '.' && $item != '..') {
// we build the new path to delete
$path = $directory.'/'.$item;

// if the new path is a directory
if(is_dir($path)) {
// we call this function with the new path
recursive_remove_directory($path);

// if the new path is a file
	}else{
// we remove the file
unlink($path);
	}
	}
	}
// close the directory
closedir($handle);
// if the option to empty is not set to true
if($empty == FALSE) {
// try to delete the now empty directory
if(!rmdir($directory)) {
// return false if not possible
return FALSE;
	}
	}
// return success
return TRUE;
	}
	}
// ------------------
recursive_remove_directory('directory_Path');

Recursive Directory Scan Function

This PHP function scans a given directory and lists all files and subdirectories it finds and has permission to read . The script recursively goes through all directories and retains the directory/content relation . It returns an array with the complete file structure and many file informations like filesize , path , name and extension . You can very easily add whatever PHP function you want , like last modified time , mime-type and more .

function scan_directory_recursively($directory, $filter=FALSE) {
// if the path has a slash at the end we remove it here
if(substr($directory,-1) == '/') {
$directory = substr($directory,0,-1);
 }

// if the path is not valid or is not a directory ...
if(!file_exists($directory) || !is_dir($directory)) {
// ... we return false and exit the function
return FALSE;

// ... else if the path is readable
 }elseif(is_readable($directory)) {
// initialize directory tree variable
$directory_tree = array();
// we open the directory
$directory_list = opendir($directory);
// and scan through the items inside
while (FALSE !== ($file = readdir($directory_list))) {
// if the filepointer is not the current directory
// or the parent directory
if($file != '.' && $file != '..') {
// we build the new path to scan
$path = $directory.'/'.$file;

// if the path is readable
if(is_readable($path)) {
// we split the new path by directories
$subdirectories = explode('/',$path);
// if the new path is a directory
if(is_dir($path)) {
// add the directory details to the file list
$directory_tree[] = array(
'path' => $path,
'name' => end($subdirectories),
'kind' => 'directory',

// we scan the new path by calling this function
'content' => scan_directory_recursively($path, $filter));

// if the new path is a file
 }elseif(is_file($path)) {
// get the file extension by taking everything after the last dot
$extension = end(explode('.',end($subdirectories)));

// if there is no filter set or the filter is set and matches
if($filter === FALSE || $filter == $extension) {
// add the file details to the file list
$directory_tree[] = array(
'path' => $path,
'name' => end($subdirectories),
'extension' => $extension,
'size' => filesize($path),
'kind' => 'file');
 }
 }
 }
 }
 }
// close the directory
closedir($directory_list);

// return file list
return $directory_tree;

// if the path is not readable ...
 }else{
// ... we return false
return FALSE;
 }
 }
// -------------------
$dir = getcwd() ;
echo $dir ."
";

$fileselection = scan_directory_recursively("$dir");
echo "We have found ". count($fileselection) . " directorys ";
echo "
<pre>";
print_r($fileselection);
echo "
";

Get the filesize of a directory and all files and subdirectories.

This PHP function scans a given directory and gets the filesize of all files it finds in the specified directory. It calls itself with all subdirectories to get the total size of the folder . By default it returns the file-size of the given directory in bytes and without any unit . If you specify that you want a human readable formatted output , this function returns the total filesize rounded in MB , KB or bytes . Keep an eye on your disquota , supervise upload folders and more . A cronjob can execute this code and if disquota is reached then let it send an email to you .


function recursive_directory_size($directory, $format=FALSE) {
$size = 0;

// if the path has a slash at the end we remove it here
if(substr($directory,-1) == '/') {
$directory = substr($directory,0,-1);
	}

// if the path is not valid or is not a directory ...
if(!file_exists($directory) || !is_dir($directory) || !is_readable($directory)) {
// ... we return -1 and exit the function
return -1;
	}
// we open the directory
if($handle = opendir($directory)) {
// and scan through the items inside
while(($file = readdir($handle)) !== false) {
// we build the new path
$path = $directory.'/'.$file;
// if the filepointer is not the current directory
// or the parent directory
if($file != '.' && $file != '..') {
// if the new path is a file
if(is_file($path)) {
// we add the filesize to the total size
$size += filesize($path);

// if the new path is a directory
	}elseif(is_dir($path)) {
// we call this function with the new path
$handlesize = recursive_directory_size($path);

// if the function returns more than zero
if($handlesize >= 0) {
// we add the result to the total size
$size += $handlesize;

// else we return -1 and exit the function
	}else{
return -1;
	}
	}
	}
	}
// close the directory
closedir($handle);
	}
// if the format is set to human readable
if($format == TRUE) {
// if the total size is bigger than 1 MB
if($size / 1048576 > 1) {
return round($size / 1048576, 1).' MB';

// if the total size is bigger than 1 KB
	}elseif($size / 1024 > 1) {
return round($size / 1024, 1).' KB';

// else return the filesize in bytes
	}else{
return round($size, 1).' bytes';
	}
	}else{
// return the total filesize in bytes
return $size;
	}
	}
// ----------------

$dir = getcwd() ;
echo $dir ."
";
$sizeInfo = recursive_directory_size($dir , TRUE);
echo $sizeInfo;

Link to the home page of these functions .

Comments»

1. PHP Developers - January 12, 2012

Hey that was really needful. Thanks for sharing. I’ll surely be looking for more.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s