php Method to Read All Filenames in Directory and Subdirectory
- 2021-07-21 08:06:30
- OfStack
This article describes the example of php reading directory and subdirectory under all the filename method, to share for your reference. The specific implementation method is as follows:
1 Generally speaking, there are quite a few ways to read the file name under the directory in php, the simplest of which is scandir, and the specific code is as follows:
$dir="./caxa/";
$file=scandir($dir);
print_r($file);
A little more complicated, from the php manual:
$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 current specified directory, but cannot read files in subdirectories. Originally, I wrote a loop to delete all directories of 1 section of code, need to delete all files one by one subdirectory, including multi-layer. But only need to read the filename, a little more complicated, find one online can be used, the original code has an error prompt, changed 1 under the reference & $data, 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('.'));
I hope this article is helpful to everyone's PHP programming.