PHP code to recursively obtain files in a directory (including subdirectories)

WBOY
Release: 2016-07-25 08:55:18
Original
927 people have browsed it
  1. /**

  2. * Recursively obtain files in directories and subdirectories
  3. * by bbs.it-home.org
  4. */

  5. function readFileFromDir($dir) {

  6. if (!is_dir($dir)) {
  7. return false;
  8. }
  9. //Open the directory
  10. $handle = opendir($dir);
  11. while (($file = readdir($handle)) !== false) {
  12. //Exclude the current directory and the previous directory A directory
  13. if ($file == "." || $file == "..") {
  14. continue;
  15. }
  16. $file = $dir . DIRECTORY_SEPARATOR . $file;
  17. //If it is a file, print it out , otherwise call recursively
  18. if (is_file($file)) {
  19. print $file . '
    ';
  20. } elseif (is_dir($file)) {
  21. readFileFromDir($file);
  22. }
  23. }
  24. }

Copy code

Calling method:

  1. $dir = '/var/www/test';
  2. readFileFromDir($dir);
Copy the code

View the php manual and find that a method scandir can also be used. This method will be used once Get all the files in a single-level directory and store them in an array. This method is not suitable when there are many files in the directory.



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