ITPub博客

首页 > > > php遍历文件夹下所有文件的代码示例

php遍历文件夹下所有文件的代码示例

作者:nt1979 时间:2019-12-05 17:28:34 0 删除 编辑

本篇文章给大家带来的内容是关于php遍历文件夹下所有文件的代码示例,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

不论是面试还是正常工作需要都会用到遍历文件夹下的所有文件,今天就记录一下笔记。废话不多说直接上代码:

<?php

/**

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

*/

function dirList($dir_path = '') {

if(is_dir($dir_path)) {

$dirs = opendir($dir_path);

if($dirs) {

while(($file = readdir($dirs)) !== false) {

if($file !== '.' && $file !== '..') {

if(is_dir($file)) {

echo $dir_path . '/' . $file . '<br>';

dirList($dir_path . '/' . $file);

} else {

echo $dir_path . '/' . $file . '<br>';

}

}

}

closedir($dirs);

}

} else {

echo '目录不存在!';

}

}

dirList('/var/www/html/php-demo');

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 !== '.' && $file !== '..') {

$tem = $dir . '/' . $file;

if(is_dir($tem)) {

$dir_list[$tem . '/'] = $file . '/';

dir_list($tem);

} else {

$dir_list[] = $file;

}

}

}

closedir($opendir);

return $dir_list;

}

}

$dir = dir_list('/var/www/html/php-demo');

var_dump($dir);

运行结果:

源代码已上传GitHub:https://github.com/cuiyuanxin/php-demo/blob/master/dir.php

以上就是php遍历文件夹下所有文件的代码示例的详细内容,更多请关注其它相关文章!

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/4822/viewspace-3150501/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-08-05

  • 博文量
    318
  • 访问量
    17304