Home >Backend Development >PHP Tutorial >Two ways to get files in a folder in php

Two ways to get files in a folder in php

尚
forward
2020-03-30 09:13:024876browse

Two ways to get files in a folder in php

Two methods for php to obtain files in a folder:

Traditional method:

When reading the contents of a folder

Use opendir readdir combined with while loop filtering to operate the current folder and parent folder

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 : [];
}

Method 2
Use the scandir function to scan the contents of the folder instead of reading in the while loop

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;
}

Recommended: PHP video tutorial

The above is the detailed content of Two ways to get files in a folder in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete