方法一:
传统方法
使用opendir readdir 和 while 循环结合
方法二:
使用 scandir 函数代替 while 循环
<?
/**
* PHP获取文件夹中的文件两种方法
*/
header('Content-Type:text/html;charset=utf-8');
/**
* 传统方法:
在读取某个文件夹下的内容的时候
使用 opendir readdir结合while循环过滤 当前文件夹和父文件夹来操作的
*/
function readFolderFiles($path)
{
$list = [];
$resource = opendir($path);
while ($file = readdir($resource))
{
//排除根目录
if ($file != ".." && $file != ".")
{
if (is_dir($path . "/" . $file))
{
//子文件夹,进行递归
$list[$file] = readFolderFiles($path . "/" . $file);
}
else
{
//根目录下的文件
$list[] = $file;
}
}
}
closedir($resource);
return $list ? $list : [];
}
/**
* 方法二
使用 scandir 函数 可以扫描文件夹下内容 代替while循环读取
*/
function scandirFolder($path)
{
$list = [];
$temp_list = scandir($path);
foreach ($temp_list as $file)
{
//排除根目录
if ($file != ".." && $file != ".")
{
if (is_dir($path . "/" . $file))
{
//子文件夹,进行递归
$list[$file] = scandirFolder($path . "/" . $file);
}
else
{
//根目录下的文件
$list[] = $file;
}
}
}
return $list;
}
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号