Home >Backend Development >PHP Tutorial >How Can I Recursively Walk a Directory and Get All File and Folder Paths Using PHP?

How Can I Recursively Walk a Directory and Get All File and Folder Paths Using PHP?

DDD
DDDOriginal
2024-12-15 06:46:15248browse

How Can I Recursively Walk a Directory and Get All File and Folder Paths Using PHP?

Walk a Directory Recursively with a PHP Function

If you need to traverse a directory and its subdirectories, seeking out every file and folder contained within, you can create a recursive PHP function to handle the task. Here's how:

Recursive Function Implementation

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

Usage

Call the function like this:

$results = getDirContents('/xampp/htdocs/WORK');
var_dump($results);

Example Output

The function will return an array containing the paths to all files and folders in the specified directory, including subdirectories. For instance, given the directory /xampp/htdocs/WORK, the output might look like this:

array (size=12)
  0 => string '/xampp/htdocs/WORK/iframe.html' (length=30)
  1 => string '/xampp/htdocs/WORK/index.html' (length=29)
  2 => string '/xampp/htdocs/WORK/js' (length=21)
  3 => string '/xampp/htdocs/WORK/js/btwn.js' (length=29)
  4 => string '/xampp/htdocs/WORK/js/qunit' (length=27)
  5 => string '/xampp/htdocs/WORK/js/qunit/qunit.css' (length=37)
  6 => string '/xampp/htdocs/WORK/js/qunit/qunit.js' (length=36)
  7 => string '/xampp/htdocs/WORK/js/unit-test.js' (length=34)
  8 => string '/xampp/htdocs/WORK/xxxxx.js' (length=30)
  9 => string '/xampp/htdocs/WORK/plane.png' (length=28)
  10 => string '/xampp/htdocs/WORK/qunit.html' (length=29)
  11 => string '/xampp/htdocs/WORK/styles.less' (length=30)

The above is the detailed content of How Can I Recursively Walk a Directory and Get All File and Folder Paths Using PHP?. For more information, please follow other related articles on the PHP Chinese website!

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
Previous article:Special Array IINext article:Special Array II