PHP使用FilesystemIterator迭代器遍历目录

/**
 * PHP高效遍历文件夹(大量文件不会卡死)
 * @param string $path 目录路径
 * @param integer $level 目录深度
 */
function fn_scandir($path = './', $level = 0) {
    $file = new FilesystemIterator($path);
    $filename = '';
    $prefix = '';
    $url = '';
    foreach ($file as $fileinfo) {
        $filename = $fileinfo->getFilename();
        $filepath = $path . $filename;
        // print_r($filepath);
        // echo $filename;
        // echo '||';
        $prefix = $level > 0 ? ('|' . str_repeat('--', $level)) : '';
        if ($fileinfo->isDir()) {
            $filepath = $filepath . '/';
            $url = '<a title="[dir] '.$filepath.'" href="?path=' . $filepath . '">' . $filename . '</a> [<a title="delete" href="?path=' . $filepath . '&action=del" onclick="return confirm(\'您确定要删除吗?\')">x</a>]';
            // echo '<strong>' . $prefix . $url . '/</strong>' . '<br />';
        } else {
            $url = '<a title="[file] '.$filepath.'" href="?path=' . $filepath . '">' . $filename . '</a> [<a title="delete" href="?path=' . $filepath . '&action=del" onclick="return confirm(\'您确定要删除吗?\')">x</a>]';
            // echo $prefix . $url . '<br />';
        }
        if ($fileinfo->isDir()) {
            fn_scandir($filepath, $level + 1);
        }
        if(is_file($filepath)){
            echo $filepath.'</br>';
        }
        
    }
}
fn_scandir('./files/');
posted @ 2020-08-06 10:54  小林不会飞  阅读(531)  评论(0编辑  收藏  举报