2010-11-16 22 views
5

Me gusta, tenemos la carpeta /images/, tiene algunos archivos dentro.¿Cómo obtener los nombres de los archivos?

Y el guión /scripts/listing.php

¿Cómo podemos obtener los nombres de los archivos dentro de la carpeta todos /images/, en listing.php?

Gracias.

Respuesta

8
<?php 

if ($handle = opendir('/path/to/files')) { 
    echo "Directory handle: $handle\n"; 
    echo "Files:\n"; 

    /* This is the correct way to loop over the directory. */ 
    while (false !== ($file = readdir($handle))) { 
     echo "$file\n"; 
    } 

    /* This is the WRONG way to loop over the directory. */ 
    while ($file = readdir($handle)) { 
     echo "$file\n"; 
    } 

    closedir($handle); 
} 
?> 

Ver: readdir()

2

Utilizando cualquiera scandir o dir hace que este problema trivial. Para obtener todos los archivos en un directorio, excepto los archivos especiales . y .. en una matriz con índices a partir de 0, uno puede combinar scandir con array_diff y array_merge:

$files = array_merge(array_diff(scandir($dir), Array('.','..'))); 
// $files now contains the filenames of every file in the directory $dir 
2

Aquí es un método que utiliza la clase SPL DirectoryIterator:

<?php 

foreach (new DirectoryIterator('../images') as $fileInfo) 
{ 
    if($fileInfo->isDot()) continue; 
    echo $fileInfo->getFilename() . "<br>\n"; 
} 

?> 
3

Incluso más fácil que readdir(), utilice pegote:

$files = glob('/path/to/files/*'); 

más información sobre glob

+1

Demasiada sobrecarga con glob – RobertPitt

1

acaba de extender en la publicación de Enrico, también hay algunos controles/modificaciones que debe hacer.

class Directory 
{ 
    private $path; 
    public function __construct($path) 
    { 
     $path = $path; 
    } 

    public function getFiles($recursive = false,$subpath = false) 
    { 
     $files = array(); 
     $path = $subpath ? $subpath : $this->path; 

     if(false != ($handle = opendir($path)) 
     { 
      while (false !== ($file = readdir($handle))) 
      { 
       if($recursive && is_dir($file) && $file != '.' && $file != '..') 
       { 
        array_merge($files,$this->getFiles(true,$file)); 
       }else 
       { 
        $files[] = $path . $file; 
       } 
      } 
     } 
     return $files; 
    } 
} 

Y el uso de este modo:

<?php 
$directory = new Directory("/"); 
$Files = $directory->getFiles(true); 
?> 

Esto le dará una lista de este modo:

/index.php 
/includes/functions.php 
/includes/.htaccess 
//... 

hoep esto ayuda.

+1

¿Por qué no usar el RecursiveDirectoryIterator/DirectoryIterator integrado ...? – ircmaxell

+0

Lo creas o no, pero algunas personas aún usan PHP4.x – RobertPitt

Cuestiones relacionadas