Home > Article > Backend Development > How to read all file names in a directory and subdirectories in php
This article mainly introduces the method of reading all the file names in the directory and subdirectories in PHP, and compares several common methods. The final example summarizes a method of reading all the file names in the directory and subdirectories in PHP, which is very useful. Practical value, friends in need can refer to it, The specific implementation method is as follows:
Generally speaking, there are many ways to read the file names in the directory in php, the simplest is scandir, the specific code is as follows:
Code As follows:
$dir="./caxa/"; $file=scandir($dir); print_r($file);
A slightly more complicated one comes from the PHP manual:
The code is as follows:
$dir = "/etc/php5/"; // Open a known directory, and proceed to read its contents if (is_dir($dir)) { if ($dh = opendir($dir)) { while (($file = readdir($dh)) !== false) { echo "filename: $file : filetype: " . filetype($dir . $file) . "\n"; } closedir($dh); } }
These can only read files in the currently specified directory, but cannot read files in subdirectories. It turned out that I had written a piece of code to delete all directories in a loop. I needed to delete all files in subdirectories one by one, including multiple layers. But you only need to read out the file name, which is a little more complicated. I found one that works online. The original code has an error message. I changed the reference to &$data as follows:
The code is as follows:
function searchDir($path,&$data){ if(is_dir($path)){ $dp=dir($path); while($file=$dp->read()){ if($file!='.'&& $file!='..'){ searchDir($path.'/'.$file,$data); } } $dp->close(); } if(is_file($path)){ $data[]=$path; } } function getDir($dir){ $data=array(); searchDir($dir,$data); return $data; } print_r(getDir('.'));