PHP leer subdirectorios y bucle a través de archivos cómo?


Necesito crear un bucle a través de todos los archivos en subdirectorios. ¿Puede ayudarme a estructurar mi código de esta manera:

$main = "MainDirectory";
loop through sub-directories {
    loop through filels in each sub-directory {
        do something with each file
    }
};

¿Puedes ayudar, por favor?

Author: Michał Rudnicki, 2010-01-06

8 answers

Use RecursiveDirectoryIterator junto con RecursiveIteratorIterator.

$di = new RecursiveDirectoryIterator('path/to/directory');
foreach (new RecursiveIteratorIterator($di) as $filename => $file) {
    echo $filename . ' - ' . $file->getSize() . ' bytes <br/>';
}
 134
Author: Michał Rudnicki,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-01-06 16:43:22

Probablemente desee usar una función recursiva para esto, en caso de que sus subdirectorios tengan sub-sub directorios

$main = "MainDirectory";

function readDirs($main){
  $dirHandle = opendir($main);
  while($file = readdir($dirHandle)){
    if(is_dir($main . $file) && $file != '.' && $file != '..'){
       readDirs($file);
    }
    else{
      //do stuff
    }
  } 
}

No probó el código, pero esto debería estar cerca de lo que desea.

 10
Author: GSto,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-23 20:46:38

Necesita agregar la ruta a su llamada recursiva.

function readDirs($path){
  $dirHandle = opendir($path);
  while($item = readdir($dirHandle)) {
    $newPath = $path."/".$item;
    if(is_dir($newPath) && $item != '.' && $item != '..') {
       echo "Found Folder $newPath<br>";
       readDirs($newPath);
    }
    else{
      echo '&nbsp;&nbsp;Found File or .-dir '.$item.'<br>';
    }
  }
}

$path =  "/";
echo "$path<br>";

readDirs($path);
 7
Author: John Marty,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-08-30 17:02:38

Me gusta glob con sus comodines:

foreach (glob("*/*.txt") as $filename) {
    echo "$filename\n";
}

Detalles y escenarios más complejos.

Pero si tiene una estructura de carpetas compleja RecursiveDirectoryIterator es definitivamente la solución.

 6
Author: Fedir RYKHTIK,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-03-28 10:49:37

Vamos, primero pruébalo tú mismo!

Lo que necesitarás:

scandir()
is_dir()

Y, por supuesto, foreach

Http://php.net/manual/en/function.is-dir.php

Http://php.net/manual/en/function.scandir.php

 5
Author: psaniko,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-12 02:26:52

Otra solución para leer con sub-directorios y sub-archivos (set correct foldername):

<?php
$path = realpath('samplefolder/yorfolder');
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path)) as $filename)
{
        echo "$filename <br/>";
}
?>
 3
Author: solution fix,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-03-28 12:15:38
    <?php
    ini_set('max_execution_time', 300);  // increase the execution time of the file (in     case the number of files or file size is more).
    class renameNewFile {

    static function copyToNewFolder() {  // copies the file from one location to another.
        $main = 'C:\xampp\htdocs\practice\demo';  // Source folder (inside this folder subfolders and inside each subfolder files are present.)
        $main1 = 'C:\xampp\htdocs\practice\demomainfolder'; // Destination Folder
        $dirHandle = opendir($main); // Open the source folder
        while ($file = readdir($dirHandle)) { // Read what's there inside the source folder
            if (basename($file) != '.' && basename($file) != '..') {   // Ignore if the folder name is '.' or '..' 
                $folderhandle = opendir($main . '\\' . $file);   // Open the Sub Folders inside the Main Folder
                while ($text = readdir($folderhandle)) {
                    if (basename($text) != '.' && basename($text) != '..') {     //  Ignore if the folder name is '.' or '..'
                        $filepath = $main . '\\' . $file . '\\' . $text;
                        if (!copy($filepath, $main1 . '\\' . $text))           // Copy the files present inside the subfolders to destination folder
                            echo "Copy failed";
                        else {
                            $fh = fopen($main1 . '\\' . 'log.txt', 'a');     // Write a log file to show the details of files copied.
                            $text1 = str_replace(' ', '_', $text);
                            $data = $file . ',' . strtolower($text1) . "\r\n";
                            fwrite($fh, $data);
                            echo $text . " is copied <br>";
                        }
                    }
                }
            }
        }
    }

    static function renameNewFileInFolder() {                //Renames the files into desired name
        $main1 = 'C:\xampp\htdocs\practice\demomainfolder';
        $dirHandle = opendir($main1);

        while ($file = readdir($dirHandle)) {
            if (basename($file) != '.' && basename($file) != '..') {
                $filepath = $main1 . '\\' . $file;
                $text1 = strtolower($filepath);
                rename($filepath, $text1);
                $text2 = str_replace(' ', '_', $text1);
                if (rename($filepath, $text2))
                    echo $filepath . " is renamed to " . $text2 . '<br/>';
            }
        }
    }

}
        renameNewFile::copyToNewFolder();
        renameNewFile::renameNewFileInFolder();
?>
 2
Author: Santosh_WebDeveloper,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-06 10:37:43
$allFiles = [];
public function dirIterator($dirName)
{
    $whatsInsideDir = scandir($dirName);
    foreach ($whatsInsideDir as $fileOrDir) {
        if (is_dir($fileOrDir)) {
            dirIterator($fileOrDir);
        }
        $allFiles.push($fileOrDir);
    }

    return $allFiles;
}
 1
Author: Ibrahim W.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-03 11:44:56