Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List all the files and folders in a Directory with PHP recursive function

Tags:

php

recursion

I'm trying to go through all of the files in a directory, and if there is a directory, go through all of its files and so on until there are no more directories to go to. Each and every processed item will be added to a results array in the function below. It is not working though I'm not sure what I can do/what I did wrong, but the browser runs insanely slow when this code below is processed, any help is appreciated, thanks!

Code:

    function getDirContents($dir){         $results = array();         $files = scandir($dir);              foreach($files as $key => $value){                 if(!is_dir($dir. DIRECTORY_SEPARATOR .$value)){                     $results[] = $value;                 } else if(is_dir($dir. DIRECTORY_SEPARATOR .$value)) {                     $results[] = $value;                     getDirContents($dir. DIRECTORY_SEPARATOR .$value);                 }             }     }      print_r(getDirContents('/xampp/htdocs/WORK')); 
like image 649
user3412869 Avatar asked Jul 16 '14 14:07

user3412869


Video Answer


2 Answers

Get all the files and folders in a directory, don't call function when you have . or ...

Your code :

<?php 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; }  var_dump(getDirContents('/xampp/htdocs/WORK')); 

Output (example) :

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) 
like image 106
Sky Voyager Avatar answered Oct 14 '22 09:10

Sky Voyager


$rii = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('path/to/folder'));  $files = array();   foreach ($rii as $file) {      if ($file->isDir()){          continue;     }      $files[] = $file->getPathname();   }    var_dump($files); 

This will bring you all the files with paths.

like image 27
zkanoca Avatar answered Oct 14 '22 08:10

zkanoca