这篇文章主要介绍了PHP采用自定义函数实现遍历目录下所有文件的方法,是PHP程序开发中常见的功能,需要的朋友可以参考下
目录的遍历是PHP程序设计中经常会用到的一个功能,很多PHP项目都有这一功能模块。今天本文就来实例解析一下PHP采用自定义函数实现遍历目录下所有文件的方法。具体方法如下:
方法一:使用readir()遍历目录
实现代码如下:
function listDir($dir)
{
if(is_dir($dir))
{
if($handle = opendir($dir))
{
while($file = readdir($handle))
{
if($file != '.' && $file != '..')
{
if(is_dir($dir.DIRECTORY_SEPARATOR.$file))
{
echo '目录名:'.$dir.DIRECTORY_SEPARATOR.''.$file.'
';
listDir($dir.DIRECTORY_SEPARATOR.$file);
}else{
echo '文件名:'.$dir.DIRECTORY_SEPARATOR.$file.'
';
}
}
}
}
closedir($handle);
}else{
echo '非有效目录!';
}
}
listDir('./phpmyadmin');
方法二:使用dir()遍历目录
本例采用dir()函数遍历,执行成功时返回Directory类实例
function tree($dir)
{
$mydir = dir($dir);
while($file = $mydir->read())
{
if($file != '.' && $file != '..')
{
if(is_dir("$dir/$file"))
{
echo '目录名:'.$dir.DIRECTORY_SEPARATOR.''.$file.'
';
tree("$dir/$file");
}else{
echo '文件名:'.$dir.DIRECTORY_SEPARATOR.$file.'
';
}
}
}
$mydir->close();
}
tree('./phpmyadmin');
除此之外,,还有很多实现目录遍历的方法,相信本文所述方法能够给大家的PHP程序设计带来一定帮助。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools