Home > Backend Development > PHP Tutorial > How to read all file names in a directory and subdirectories in php_PHP tutorial

How to read all file names in a directory and subdirectories in php_PHP tutorial

WBOY
Release: 2016-07-13 10:16:32
Original
1060 people have browsed it

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

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:

Copy code The code is as follows:
$dir="./caxa/";
$file=scandir($dir);
print_r($file);

The slightly more complicated one comes from the php manual:

Copy code 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 online that works. The original code has an error message. I changed the reference to &$data as follows:

Copy code 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('.'));

I hope this article will be helpful to everyone’s PHP programming design.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/897008.htmlTechArticleHow to read all file names in a directory and subdirectories with php. This example describes how to read directories and subdirectories with php The method of naming all files in the directory is shared with everyone for your reference. Specific implementation method...
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template