How to check if a file exists within a directory, or sub directory of the parent?

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 within the specified directory to search does not have adequate permissions, the function will return false. Use this below function,

<?php

function recursive_file_exists($filename, $directory)
{
try
{
foreach(new recursiveIteratorIterator( new recursiveDirectoryIterator($directory)) as $file)
{

if( $directory.’/’.$filename == $file )
{
return true;
}
}
return false;
}
catch(Exception $e)
{
return false;
}
}

?>

Example:

<?php

if(recursive_file_exists(‘file.php’, ‘/www/html’))
{
echo ‘file found’;
}
else
{
echo ‘File Not Found’;
}
?>

You can leave a response, or trackback from your own site.

One Response to “How to check if a file exists within a directory, or sub directory of the parent?”

  1. vivek says:

    hi dear
    this code is working fine
    just copy and paste
    work it
    thanks lot

Leave a Reply