Home >Backend Development >PHP Tutorial >php reads all files in a directory

php reads all files in a directory

WBOY
WBOYOriginal
2016-07-30 13:31:121658browse

/**
* Get all directories and files contained in the input directory
* Return as an associative array
* author: flynetcn
*/
function deepScanDir($dir)
{
    $fileArr = array();
    $dirArr = array();
    $dir = rtrim($dir, '//');
    if(is_dir($dir)){
        $dirHandle = opendir($dir);
        while(false !== ($fileName = readdir($dirHandle))){
            $subFile = $dir . DIRECTORY_SEPARATOR . $fileName;
            if(is_file($subFile)){
                $fileArr[] = $subFile;
            } elseif (is_dir($subFile) && str_replace('.', '', $fileName)!=''){
                $dirArr[] = $subFile;
                $arr = deepScanDir($subFile);
                $dirArr = array_merge($dirArr, $arr['dir']);
                $fileArr = array_merge($fileArr, $arr['file']);
            }
        }
        closedir($dirHandle);
    }
    return array('dir'=>$dirArr, 'file'=>$fileArr);
}
//示例
$dir = '/var/htdocs/w4/article';
$arr = deepScanDir($dir);
print_r($arr);
/**
* Get all the files contained in the input directory
* Return as an array
* author: flynetcn
*/
function get_dir_files($dir)
{
    if (is_file($dir)) {
        return array($dir);
    }
    $files = array();
    if (is_dir($dir) && ($dir_p = opendir($dir))) {
        $ds = DIRECTORY_SEPARATOR;
        while (($filename = readdir($dir_p)) !== false) {
            if ($filename=='.' || $filename=='..') { continue; }
            $filetype = filetype($dir.$ds.$filename);
            if ($filetype == 'dir') {
                $files = array_merge($files, get_dir_files($dir.$ds.$filename));
            } elseif ($filetype == 'file') {
                $files[] = $dir.$ds.$filename;
            }
        }
        closedir($dir_p);
    }
    return $files;
}

以上就介绍了php 读取某目录下的所有文件,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn