PHP gets all file names under the directory and subdirectory

Youhuang Xiaozhu 2021-10-14 08:08:13

 

 

Ideas : First, get all the file names in a directory. You can use scandir() function .scandir() Function returns an array of files and directories in the specified directory . Because the returned data does not contain the files in the subdirectory , So you can use recursive processing .

/**
* @param $dir File path to find
* @param $dir_array An array of file names
*/
function find_files($dir, &$dir_array)
{
// Read all files and directories in the current directory ( Does not contain files in subdirectories )
$files = scandir($dir);
if (is_array($files)) {
foreach ($files as $val) {
// skip . and ..
if ($val == '.' || $val == '..')
continue;
// Determine if it's a directory 
if (is_dir($dir . '/' . $val)) {
// Add the current directory to the array 
$dir_array[$dir][] = $val;
// Recursion continues to look down 
find_files($dir . '/' . $val, $dir_array);
} else {
// Not a directory, you also need to add the current file to the array 
$dir_array[$dir][] = $val;
}
}
}
}
// call 
$folder_list = array();
find_files('/demo/', $folder_list);
var_dump($folder_list);

 

Please bring the original link to reprint ,thank
Similar articles