Home > Backend Development > PHP Tutorial > How Can I Recursively Find Files and Folders in PHP Without Performance Issues?

How Can I Recursively Find Files and Folders in PHP Without Performance Issues?

Linda Hamilton
Release: 2024-11-25 21:17:27
Original
198 people have browsed it

How Can I Recursively Find Files and Folders in PHP Without Performance Issues?

Finding Files and Folders Recursively with PHP

To traverse a directory's contents and all subdirectories, a recursive function is employed. However, the code provided has a performance issue, causing the browser to slow down significantly.

The Issue

The function doesn't exclude "." and ".." directories from the recursive calls, leading to an infinite loop and slow execution.

The Fix

To address this issue, we modified the code as follows:

function getDirContents($dir, &$results = array()) {
    $files = scandir($dir);

    foreach ($files as $key => $value) {
        $path = realpath($dir . DIRECTORY_SEPARATOR . $value);
        if (!is_dir($path)) {
            $results[] = $path;
        } else if ($value != "." && $value != "..") {
            getDirContents($path, $results);
            $results[] = $path;
        }
    }

    return $results;
}
Copy after login

Exclusion of "." and ".."

We added conditions to exclude "." and ".." directories from the recursive calls. These directories represent the current and parent directories, respectively, and their inclusion would create an infinite loop.

Usage

To use the function, simply provide the path to the directory you want to traverse:

var_dump(getDirContents('/xampp/htdocs/WORK'));
Copy after login

This code will return an array containing the complete list of files and folders within the specified directory. Each entry will be the full path to the file or folder.

The above is the detailed content of How Can I Recursively Find Files and Folders in PHP Without Performance Issues?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template