Home  >  Article  >  Backend Development  >  Detailed example of how to use php to read all file names in a subdirectory

Detailed example of how to use php to read all file names in a subdirectory

伊谢尔伦
伊谢尔伦Original
2017-07-08 11:49:271416browse

The example in this article describes the method of reading all file names in a directory and subdirectories in PHP, and shares it with you for your reference. The specific implementation method is as follows:

Generally speaking, there are many ways to read file names in a directory in PHP. The simplest one is scandir. The specific code is as follows:

The code is as follows:

$dir="./caxa/";
$file=scandir($dir);
print_r($file);

The 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 Both 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 the file name, which is a little more complicated. I found one online that works. 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('.'));


The above is the detailed content of Detailed example of how to use php to read all file names in a subdirectory. For more information, please follow other related articles on the PHP Chinese website!

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