php遍历文件夹、文件

php遍历文件夹、文件

<?php
$path = '/';
foreach_file($path);//传入需要遍历的文件夹路径

function foreach_file($path)
{
    if(is_dir($path))//判断目录是否存在
    {
        //opendir()返回一个目录句柄,失败返回false
        if($current_dir = opendir($path))
        {
            //读取目录句柄里的每一个文件,读到最后会返回false
            while(($file = readdir($current_dir)) !== false)
            {
                $sub_dir = $path . DIRECTORY_SEPARATOR . $file;//拼接文件路径

                if($file == '.' || $file == '..')//判断是否是..和.,如果是则continue
                {
                    continue;
                }
                else if(is_dir($sub_dir))//判断是不是文件夹,如果是则递归进入该文件夹
                {
                    foreach_file($sub_dir);
                }
                else
                {
                    //这里读到文件,做相应的处理
                    echo 'File in Directory ' . $path . ': ' . $file . '<br>';
                }
            }
        }
    }
}
?>

猜你喜欢

转载自blog.csdn.net/wodecc_u/article/details/72725411
今日推荐