SCC SCC - 2 months ago 10
PHP Question

How to find a file recursively in folders using PHP?

How to find a file in folders with sub name of the file means the file need to be searched is not fully named but it is a part of the name for example I want to search the file namely 'hello_world_123.png'. I did not enter full name of the file but one or some words only, for example the 'world_' is my input but the code should search the full name of file.

In short the searching may work like operating system's search in file explorer or file manager.

My code as below but I am stuck with matching the name of file in if condition.

$file_name_ = 'recursive-1.php';
$dir = new RecursiveDirectoryIterator( $folder_path, RecursiveDirectoryIterator::SKIP_DOTS);
$it = new RecursiveIteratorIterator($dir);

foreach($it as $file) {

$file_info = pathinfo($file);

$patt = '/^(\w+)\.+('.$file_name_.')\.+(\w+)*$/';
$result = preg_match($patt,strtolower( $file_info['basename'] ),$match );
if ( $result ) {
echo 'File found';
} else {
echo 'File not found';
}
}

SCC SCC
Answer

To find the file in directory recursively, with or without extension, the following code is helpful. The file name is not complete name (the part of the file name) so the strpos() function will find the position of file name which is partial.

$file_name_ = 'recursive-1.php';

//Splitting the file to get the file name without extension
$file_name_ = explode('.',$file_name_);
$file_name_ = $file_name_[0];

$dir = new RecursiveDirectoryIterator( $folder_path,   RecursiveDirectoryIterator::SKIP_DOTS);
$it = new RecursiveIteratorIterator($dir);  

//looping for all files in given directory
foreach($it as $file) {     

    $file_info = pathinfo($file);       
    //$patt = '/^(\w+)\.+('.$file_name_.')\.+(\w+)*$/';
    //$result = preg_match($patt,strtolower( $file_info['basename'] ),$match );       
    //$result = strpos(strtolower($file_info['filename']),strtolower( $file_name_));    
    $result = stripos($file_info['filename'], $file_name_); 
    if ( $result === flase ) {    
        echo 'File not found';
    } else {
        echo 'File found';
    }
}