Home  >  Article  >  Backend Development  >  Example of how to traverse all files in a folder using PHP

Example of how to traverse all files in a folder using PHP

little bottle
little bottleforward
2019-04-19 12:00:294010browse

Whether it is for interviews or normal work, it is necessary to traverse all files in a folder. Let me share with you an example of how to traverse all files in a folder using PHP for your reference.

<?php

/**
* 遍历当前文件夹展示所有的文件和目录
*/

function dirList($dir_path = &#39;&#39;) {
    if(is_dir($dir_path)) {
        $dirs = opendir($dir_path);
        if($dirs) {
            while(($file = readdir($dirs)) !== false) {
                if($file !== &#39;.&#39; && $file !== &#39;..&#39;) {
                    if(is_dir($file)) {
                        echo $dir_path . &#39;/&#39; . $file . &#39;<br>&#39;;
                        dirList($dir_path . &#39;/&#39; . $file);
                    } else {
                        echo $dir_path . &#39;/&#39; . $file . &#39;<br>&#39;;
                    }
                }
            }
            closedir($dirs);
        }
    } else {
        echo &#39;目录不存在!&#39;;
    }
}

dirList(&#39;/var/www/html/php-demo&#39;);

function dir_list($dir) {
    if(!is_dir($dir)) return false;
    $dir_list = array();
    $opendir = opendir($dir);
    if($opendir) {
        while(($file = readdir($opendir)) !== false) {
            if($file !== &#39;.&#39; && $file !== &#39;..&#39;) {
                $tem = $dir . &#39;/&#39; . $file;
                if(is_dir($tem)) {
                    $dir_list[$tem . &#39;/&#39;] = $file . &#39;/&#39;;
                    dir_list($tem);
                } else {
                    $dir_list[] = $file;
                }
            }
        }
        closedir($opendir);
        return $dir_list;
    }
}

$dir = dir_list(&#39;/var/www/html/php-demo&#39;);
var_dump($dir);

Running results:

Example of how to traverse all files in a folder using PHP

##Related tutorials:

PHP video tutorial

The above is the detailed content of Example of how to traverse all files in a folder using PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete