Recursive File Exists
Bookmark on del.icio.us
Tweet
Tweet
Recently a request to PHPAsKS asked how to check if a file exists within a directory, or sub directory of the parent. With the use of the PHP SPL recursiveDirectoryIterator this is quite simple. Care should be taken that if any sub directory withing the specified directory to search does not have adequate permissions, the function will return false.
<?php
/*
* @Search recursively for a file in a given directory
*
* @param string $filename The file to find
*
* @param string $directory The directory to search
*
* @return bool
*
*/
function recursive_file_exists($filename, $directory)
{
try
{
/*** loop through the files in directory ***/
foreach(new recursiveIteratorIterator( new recursiveDirectoryIterator($directory)) as $file)
{
/*** if the file is found ***/
if( $directory.'/'.$filename == $file )
{
return true;
}
}
/*** if the file is not found ***/
return false;
}
catch(Exception $e)
{
/*** if the directory does not exist or the directory
or a sub directory does not have sufficent
permissions return false ***/
return false;
}
}
?>
Example Usage
<?php
/*** search for file.php ***/
if(recursive_file_exists('file.php', '/www/html'))
{
echo 'file found';
}
else
{
echo 'File Not Found';
}
?>
No comments yet.