PHP :: Aufgabe #2 :: Lösung #10

6 Lösungen Lösungen öffentlich
#2

Ordner rekursiv auslesen

Anfänger - PHP von ne0n - 10.08.2012 um 17:38 Uhr
Erstelle in einer Klasse eine Funktion die einen Ordner rekursiv durchläuft und die Unterverzeichnisse und Dateien ausgibt.
#10
vote_ok
von Jidoka86 (660 Punkte) - 08.05.2016 um 21:48 Uhr
Quellcode ausblenden PHP-Code
<?php
  /**
   *
   */
  class RecursivFolderPrinter
  {
    public function doPrint($path){
      if(!file_exists($path)){
        throw new Exception("File/Folder {$path} does not exist.");
      }
      //the only output call is here
      echo realpath($path) . "\n";
      //here goes the recursive logic
      if(is_dir($path)){
          $files = scandir($path);
          foreach ($files as $file) {
            if($file != "." and $file != ".."){
              //here the root path must be prepended to prevent infinite loops
              //in case of a child folder has the same name as it's parent.
              //furthermore it's necessary to jump in to deeper levels.
              $this->doPrint($path."/".$file);
          }
        }
      }
    }
  }

  $folderPrinter = new RecursivFolderPrinter();
  $folderPrinter->doPrint("./");

Kommentare:

Für diese Lösung gibt es noch keinen Kommentar

Bitte melden Sie sich an um eine Kommentar zu schreiben.
Kommentar schreiben