Home  >  Article  >  Backend Development  >  How to read all file names in a directory and subdirectories in php

How to read all file names in a directory and subdirectories in php

巴扎黑
巴扎黑Original
2017-06-09 11:42:203088browse

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('.'));
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:php regular length limitNext article:php regular length limit