Exploración del directorio/archivo PHP

  • ScottG
  • Proficient
  • Proficient
  • No Avatar
  • Registrado: Jul 06, 2010
  • Mensajes: 261
  • Status: Offline

Nota Diciembre 7th, 2012, 1:25 pm

Así que he hecho recientemente una función para obtener todos los archivos y carpetas de una carpeta. Pensé que ID pone la función aquí así que si alguien necesita usarlo o para ver si alguien ha tenido cambios y mejoras que le gustaría compartir.

PHP Código: [ Select ]
// This funtion will get all files and directories of folder.
function get_tree($config = array()) {
       
        // Setup the defaults. I choose to set it up like this due to how cluttered the normal way looked
        $file_types                  = empty($config['file_types']) ? array() : $config['file_types'];
        $path                        = empty($config['path']) ? __DIR__ : realpath($config['path']);
        $include_directories         = (empty($config['include_directories']) || $config['include_directories'] === false) ? false : true;
        $directories_only            = (empty($config['directories_only']) || $config['directories_only'] === false) ? false : true;
        $skip_dots                   = !isset($config['skip_dots']) ? true : (($config['skip_dots'] === false) ? false : true);
        $remove_root                 = !isset($config['remove_root']) ? true : (($config['remove_root'] === false) ? false : true);
 
        // Make an array to hold the paths
        $return_array = array();
       
        // Setup the directory
        $directory = new RecursiveDirectoryIterator($path);
       
        // Get the directory and files
        $objects = new RecursiveIteratorIterator($directory, RecursiveIteratorIterator::SELF_FIRST);
       
        // Make sure the file types array is empty if $directories_only is set to true
        $file_types = ($directories_only) ? array() : $file_types;
       
        // Setup force extenstion add
        $force_extenstions = ((empty($file_types) && $include_directories && !$directories_only) || (empty($file_types) && !$include_directories && !$directories_only)) ? true : false;
       
        // See if we want to include directories
        if($include_directories || $directories_only) {
               
                // Add to file types
                $file_types[] = 'directory';
               
                // Check to see if we what to add the dot paths
                if(!$skip_dots) {
                       
                        // Add to file types
                        $file_types[] = 'dot_directory';
                       
                }
               
        }
       
        // Loop through the directory and files
        foreach($objects as $name => $object) {
               
                // Get the info on the path
                $info = pathinfo($name);
               
                // Check $force_extenstions
                if($force_extenstions) {
                       
                        // Check to see if we already have the extenstion
                        if(!in_array($info['extension'], $file_types)) {
                               
                                // Add the extension
                                $file_types[] = $info['extension'];
                               
                        }
                       
                }
               
                // Fix blank
                $info['extension'] = (empty($info['extension'])) ? ((substr($name,-1) == '.') ? 'dot_directory' : 'directory') : $info['extension'];
               
                // Check for the file types
                if(in_array(strtolower($info['extension']), $file_types)) {
                       
                        // See if we want to remove the root
                        if($remove_root) {
                               
                                // Add to the array
                                $return_array[] = str_replace($path, '', $name);
                       
                        } else {
                               
                                // Add to the array
                                $return_array[] = $name;
                               
                        }
                       
                }
 
        }
       
        // Return the array
        return $return_array;
       
}
 
// The config array I decided to go this route so I didn't have a bunch of optional variables just to get one functional part of the function
// for example: instead of get_tree(array(),false, true, false); I could simply do get_tree(array("directories_only" => true, "skip_dots" => false));
//
// Config array options
//
// $config = array(
//      "file_types" => array('php','js'),
//      "path" => '../path/to/folder',
//      "include_directories" => true,
//      "directories_only" => true,
//      "skip_dots" => true,
//      "remove_root" => true
//      );
//
// "file_types"          - This is the extensions of the files you want to find.
// "path"                - Path to the folder you want to scan.
// "include_directories" - If set to true this will return both the directories and the files.
// "directories_only"    - If this is set to true is will over ride the file_types array and return only the directories.
// "skip_dots"           - If this is set to true is will skip over the '.' and '..' paths.
// "remove_root"         - This will remove the root directory path up to the path variable set if set to true.
//
// Defaults
//
// "file_types"          - array().
// "path"                - __DIR__.
// "include_directories" - false.
// "directories_only"    - false.
// "skip_dots"           - true.
// "remove_root"         - true.
//
// Usage
//
// Get all files only
$test = get_tree();
 
// Get only php files
$test = get_tree(array("file_types" => array('php')));
 
// Get php and js files
$test = get_tree(array("file_types" => array('php', js)));
 
// Get only php files and the subdirectories
$test = get_tree(array("file_types" => array('php'), "include_directories" => true));
 
// Get only directories
$test = get_tree(array("directories_only" => true));
 
// Get only directories with dot paths
$test = get_tree(array("directories_only" => true, "skip_dots" => false));
 
// Get all files with root path
$test = get_tree(array("remove_root" => false));
 
 
  1. // This funtion will get all files and directories of folder.
  2. function get_tree($config = array()) {
  3.        
  4.         // Setup the defaults. I choose to set it up like this due to how cluttered the normal way looked
  5.         $file_types                  = empty($config['file_types']) ? array() : $config['file_types'];
  6.         $path                        = empty($config['path']) ? __DIR__ : realpath($config['path']);
  7.         $include_directories         = (empty($config['include_directories']) || $config['include_directories'] === false) ? false : true;
  8.         $directories_only            = (empty($config['directories_only']) || $config['directories_only'] === false) ? false : true;
  9.         $skip_dots                   = !isset($config['skip_dots']) ? true : (($config['skip_dots'] === false) ? false : true);
  10.         $remove_root                 = !isset($config['remove_root']) ? true : (($config['remove_root'] === false) ? false : true);
  11.  
  12.         // Make an array to hold the paths
  13.         $return_array = array();
  14.        
  15.         // Setup the directory
  16.         $directory = new RecursiveDirectoryIterator($path);
  17.        
  18.         // Get the directory and files
  19.         $objects = new RecursiveIteratorIterator($directory, RecursiveIteratorIterator::SELF_FIRST);
  20.        
  21.         // Make sure the file types array is empty if $directories_only is set to true
  22.         $file_types = ($directories_only) ? array() : $file_types;
  23.        
  24.         // Setup force extenstion add
  25.         $force_extenstions = ((empty($file_types) && $include_directories && !$directories_only) || (empty($file_types) && !$include_directories && !$directories_only)) ? true : false;
  26.        
  27.         // See if we want to include directories
  28.         if($include_directories || $directories_only) {
  29.                
  30.                 // Add to file types
  31.                 $file_types[] = 'directory';
  32.                
  33.                 // Check to see if we what to add the dot paths
  34.                 if(!$skip_dots) {
  35.                        
  36.                         // Add to file types
  37.                         $file_types[] = 'dot_directory';
  38.                        
  39.                 }
  40.                
  41.         }
  42.        
  43.         // Loop through the directory and files
  44.         foreach($objects as $name => $object) {
  45.                
  46.                 // Get the info on the path
  47.                 $info = pathinfo($name);
  48.                
  49.                 // Check $force_extenstions
  50.                 if($force_extenstions) {
  51.                        
  52.                         // Check to see if we already have the extenstion
  53.                         if(!in_array($info['extension'], $file_types)) {
  54.                                
  55.                                 // Add the extension
  56.                                 $file_types[] = $info['extension'];
  57.                                
  58.                         }
  59.                        
  60.                 }
  61.                
  62.                 // Fix blank
  63.                 $info['extension'] = (empty($info['extension'])) ? ((substr($name,-1) == '.') ? 'dot_directory' : 'directory') : $info['extension'];
  64.                
  65.                 // Check for the file types
  66.                 if(in_array(strtolower($info['extension']), $file_types)) {
  67.                        
  68.                         // See if we want to remove the root
  69.                         if($remove_root) {
  70.                                
  71.                                 // Add to the array
  72.                                 $return_array[] = str_replace($path, '', $name);
  73.                        
  74.                         } else {
  75.                                
  76.                                 // Add to the array
  77.                                 $return_array[] = $name;
  78.                                
  79.                         }
  80.                        
  81.                 }
  82.  
  83.         }
  84.        
  85.         // Return the array
  86.         return $return_array;
  87.        
  88. }
  89.  
  90. // The config array I decided to go this route so I didn't have a bunch of optional variables just to get one functional part of the function
  91. // for example: instead of get_tree(array(),false, true, false); I could simply do get_tree(array("directories_only" => true, "skip_dots" => false));
  92. //
  93. // Config array options
  94. //
  95. // $config = array(
  96. //      "file_types" => array('php','js'),
  97. //      "path" => '../path/to/folder',
  98. //      "include_directories" => true,
  99. //      "directories_only" => true,
  100. //      "skip_dots" => true,
  101. //      "remove_root" => true
  102. //      );
  103. //
  104. // "file_types"          - This is the extensions of the files you want to find.
  105. // "path"                - Path to the folder you want to scan.
  106. // "include_directories" - If set to true this will return both the directories and the files.
  107. // "directories_only"    - If this is set to true is will over ride the file_types array and return only the directories.
  108. // "skip_dots"           - If this is set to true is will skip over the '.' and '..' paths.
  109. // "remove_root"         - This will remove the root directory path up to the path variable set if set to true.
  110. //
  111. // Defaults
  112. //
  113. // "file_types"          - array().
  114. // "path"                - __DIR__.
  115. // "include_directories" - false.
  116. // "directories_only"    - false.
  117. // "skip_dots"           - true.
  118. // "remove_root"         - true.
  119. //
  120. // Usage
  121. //
  122. // Get all files only
  123. $test = get_tree();
  124.  
  125. // Get only php files
  126. $test = get_tree(array("file_types" => array('php')));
  127.  
  128. // Get php and js files
  129. $test = get_tree(array("file_types" => array('php', js)));
  130.  
  131. // Get only php files and the subdirectories
  132. $test = get_tree(array("file_types" => array('php'), "include_directories" => true));
  133.  
  134. // Get only directories
  135. $test = get_tree(array("directories_only" => true));
  136.  
  137. // Get only directories with dot paths
  138. $test = get_tree(array("directories_only" => true, "skip_dots" => false));
  139.  
  140. // Get all files with root path
  141. $test = get_tree(array("remove_root" => false));
  142.  
  143.  


Si alguno encuentra este útil gran si tiene preguntas, inquietudes o mejoras Id encantan escucharlos
  • Anonymous
  • Bot
  • No Avatar
  • Registrado: 25 Feb 2008
  • Mensajes: ?
  • Loc: Ozzuland
  • Status: Online

Nota Diciembre 7th, 2012, 1:25 pm

  • spork
  • Brewmaster
  • Silver Member
  • Avatar de Usuario
  • Registrado: Sep 22, 2003
  • Mensajes: 6129
  • Loc: Seattle, WA
  • Status: Offline

Nota Diciembre 7th, 2012, 3:28 pm

¿Se ofrece algún beneficio sobre scandir() ?
The Beer Monocle. Classy.
  • ScottG
  • Proficient
  • Proficient
  • No Avatar
  • Registrado: Jul 06, 2010
  • Mensajes: 261
  • Status: Offline

Nota Diciembre 7th, 2012, 4:39 pm

Esta función analiza todos los subdirectorios en la carpeta determinada y se aprovecha de la clase RecursiveDirectoryIterator que reduce la cantidad de código necesario para realizar la misma tarea con scandir

Por ejemplo
PHP Código: [ Select ]
<?php
 
// Quick recursive scandir
function recursiveScanDir($dir){
    $files = scandir($dir);
    foreach($files as $file){
        if ($file != '.' && $file != '..'){
            if (is_dir($dir . DIRECTORY_SEPARATOR . $file)){
                recursiveScanDir($dir . DIRECTORY_SEPARATOR . $file);
            }else{
                echo $dir . DIRECTORY_SEPARATOR . $file . PHP_EOL . '<br>';
            }
        }
    }
}
 
recursiveScanDir(__DIR__);
?>
<br>
<br>
 
<?php
 
// RecursiveDirectoryIterator in this function
$directory = new RecursiveDirectoryIterator(__DIR__);
$objects = new RecursiveIteratorIterator($directory, RecursiveIteratorIterator::SELF_FIRST);
foreach($objects as $name => $object) {
        echo $name. '<br>';
}
 
?>
 
  1. <?php
  2.  
  3. // Quick recursive scandir
  4. function recursiveScanDir($dir){
  5.     $files = scandir($dir);
  6.     foreach($files as $file){
  7.         if ($file != '.' && $file != '..'){
  8.             if (is_dir($dir . DIRECTORY_SEPARATOR . $file)){
  9.                 recursiveScanDir($dir . DIRECTORY_SEPARATOR . $file);
  10.             }else{
  11.                 echo $dir . DIRECTORY_SEPARATOR . $file . PHP_EOL . '<br>';
  12.             }
  13.         }
  14.     }
  15. }
  16.  
  17. recursiveScanDir(__DIR__);
  18. ?>
  19. <br>
  20. <br>
  21.  
  22. <?php
  23.  
  24. // RecursiveDirectoryIterator in this function
  25. $directory = new RecursiveDirectoryIterator(__DIR__);
  26. $objects = new RecursiveIteratorIterator($directory, RecursiveIteratorIterator::SELF_FIRST);
  27. foreach($objects as $name => $object) {
  28.         echo $name. '<br>';
  29. }
  30.  
  31. ?>
  32.  


No la he probado para las diferencias de rendimiento entre los dos.
  • demonmaestro
  • Gold Member
  • Gold Member
  • Avatar de Usuario
  • Registrado: Jun 21, 2006
  • Mensajes: 484
  • Loc: Conroe, Texas
  • Status: Offline

Nota Diciembre 7th, 2012, 4:51 pm

enfriar la idea pero hay un error...

Quote:
Fatal error: excepción no capturada "RuntimeException" con el nombre de directorio del mensaje no debe estar vacía. en /test.php:22 seguimiento de la pila: #0 /test.php(22): RecursiveDirectoryIterator -&gt; __construct () #1 {principal} en /test.php on line 23


y es que la línea
PHP Código: [ Select ]
$directory = new RecursiveDirectoryIterator($path);
Thanks, Josh --DemonMaestro
www.LilNetwork.com
Fun Website www.ShoutsCloud.com
  • ScottG
  • Proficient
  • Proficient
  • No Avatar
  • Registrado: Jul 06, 2010
  • Mensajes: 261
  • Status: Offline

Nota Diciembre 7th, 2012, 5:35 pm

¿Es desde el segundo bloque de código? Si ése es el caso copié el corazón de la función anterior y se olvidó de agregar una ruta de acceso. También no probar la segunda parte porque estaba dando un ejemplo. Hice el cambio y si se activa
PHP Código: [ Select ]
$directory = new RecursiveDirectoryIterator($path);
 
// To
 
$directory = new RecursiveDirectoryIterator(__DIR__);
 
// Or
 
$directory = new RecursiveDirectoryIterator('/your/folder/path');
 
  1. $directory = new RecursiveDirectoryIterator($path);
  2.  
  3. // To
  4.  
  5. $directory = new RecursiveDirectoryIterator(__DIR__);
  6.  
  7. // Or
  8.  
  9. $directory = new RecursiveDirectoryIterator('/your/folder/path');
  10.  


Entonces el error debe desaparecer

Publicar Información

  • Total de mensajes en este tema: 5 mensajes
  • Usuarios navegando por este Foro: No hay usuarios registrados visitando el Foro y 242 invitados
  • No puede abrir nuevos temas en este Foro
  • No puede responder a temas en este Foro
  • No puede editar sus mensajes en este Foro
  • No puede borrar sus mensajes en este Foro
  • No puede enviar adjuntos en este Foro
 
 

© 2011 Unmelted, LLC. Ozzu® es una marca registrada de Unmelted, LLC