Home  >  Article  >  Backend Development  >  php递归获取目录内文件(包含子目录)的代码

php递归获取目录内文件(包含子目录)的代码

WBOY
WBOYOriginal
2016-07-25 08:55:18812browse
  1. /**

  2. * 递归获取目录与子目录中的文件
  3. * by bbs.it-home.org
  4. */
  5. function readFileFromDir($dir) {

  6. if (!is_dir($dir)) {
  7. return false;
  8. }
  9. //打开目录
  10. $handle = opendir($dir);
  11. while (($file = readdir($handle)) !== false) {
  12. //排除掉当前目录和上一个目录
  13. if ($file == "." || $file == "..") {
  14. continue;
  15. }
  16. $file = $dir . DIRECTORY_SEPARATOR . $file;
  17. //如果是文件就打印出来,否则递归调用
  18. if (is_file($file)) {
  19. print $file . '
    ';
  20. } elseif (is_dir($file)) {
  21. readFileFromDir($file);
  22. }
  23. }
  24. }
复制代码

调用方式:

  1. $dir = '/var/www/test';
  2. readFileFromDir($dir);
复制代码

查看php手册,发现一个方法scandir也可以使用,此方法会一次性获取单级目录下的所有文件,存放到数组中。 当目录中文件较多时,此方法不太适用。



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