How to read all the file names under directories and subdirectories in PHP _php tips

Source: Internet
Author: User

This article describes the PHP reading directory and subdirectories of all the file name method, share for everyone to reference. The implementation methods are as follows:

In general, PHP read the directory in the way the file name is indeed a lot, the simplest is scandir, the specific code is as follows:

Copy Code code as follows:
$dir = "./caxa/";
$file =scandir ($dir);
Print_r ($file);

Slightly more complex, from the PHP manual:

Copy Code code 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, and files in the subdirectory cannot be read. I've written myself a loop. Deletes a piece of code for all directories, and you need to delete all files, including multiple layers, on a subdirectory-by-directory basis. But just read out the file name, a little more complex, the Internet to find a can use, the original code has the wrong hint, changed the reference & $data place, as follows:

Copy Code code 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 help you with your PHP program design.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.