Two ways to get files in a folder in php

Release: 2023-04-08 13:50:01
forward
4832 people have browsed it

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

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;
}
Copy after login

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!

Related labels:
php
source:csdn.net
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template