Home > Backend Development > PHP Tutorial > Code example for php to traverse all files in a folder

Code example for php to traverse all files in a folder

不言
Release: 2023-04-05 13:18:01
forward
6211 people have browsed it

This article brings you code examples about PHP traversing all files in a folder. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Whether it is an interview or normal work, you will need to traverse all the files in the folder. Take notes today. Without further ado, let’s get straight to the code:

<?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);
Copy after login

Running results:

Code example for php to traverse all files in a folder

The source code has been uploaded to GitHub: https://github .com/cuiyuanxin/php-demo/blob/master/dir.php

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

Related labels:
php
source:cnblogs.com
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