php遍历文件夹和文件列表示例分享

前端技术 2023/09/02 PHP

为PHP遍历目录和文件列表写了一个简单的类,并附上使用实例,大家参考使用吧

复制代码 代码如下:

<?php
define(\'DS\', DIRECTORY_SEPARATOR);

class getDirFile{

    //返回数组
    private $DirArray  = array();
    private $FileArray = array();
    private $DirFileArray = array();

    private $Handle,$Dir,$File;

    //获取目录列表
    public function getDir( & $Dir ){
        if( is_dir($Dir) ){
            if( false != ($Handle = opendir($Dir)) ){
                while( false != ($File = readdir($Handle)) ){
                    if( $File!=\'.\' && $File!=\'..\' && !strpos($File,\'.\') ){
                        $DirArray[] = $File;
                    }
                }
                closedir( $Handle );
            }
        }else{
            $DirArray[] = \'[Path]:\\\'\'.$Dir.\'\\\' is not a dir or not found!\';
        }
        return $DirArray;
    }

    //获取文件列表
    public function getFile( & $Dir ){
        if( is_dir($Dir) ){
            if( false != ($Handle = opendir($Dir)) ) {
                while( false != ($File = readdir($Handle)) ){
                    if( $File!=\'.\' && $File!=\'..\' && strpos($File,\'.\') ){
                        $FileArray[] = $File;
                    }
                }
                closedir( $Handle );
            }
        }else{
            $FileArray[] = \'[Path]:\\\'\'.$Dir.\'\\\' is not a dir or not found!\';
        }
        return $FileArray;
    }

    //获取目录/文件列表
    public function getDirFile( & $Dir ){
        if( is_dir($Dir) ){
            $DirFileArray[\'DirList\'] = $this->getDir( $Dir );
            if( $DirFileArray ){
                foreach( $DirFileArray[\'DirList\'] as $Handle ){
                    $File = $Dir.DS.$Handle;
                    $DirFileArray[\'FileList\'][$Handle] = $this->getFile( $File );
                }
            }
        }else{
            $DirFileArray[] = \'[Path]:\\\'\'.$Dir.\'\\\' is not a dir or not found!\';
        }
        return $DirFileArray;
    }

}
?>

本文地址:https://www.stayed.cn/item/3428

转载请注明出处。

本站部分内容来源于网络,如侵犯到您的权益,请 联系我

我的博客

人生若只如初见,何事秋风悲画扇。