2010-11-16 4 views
5

Come, abbiamo cartella /images/, ha alcuni file all'interno.Come ottenere i nomi dei file?

e lo script /scripts/listing.php

Come possiamo ottenere i nomi dei tutti i file all'interno della cartella /images/, in listing.php?

Grazie.

risposta

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); 
} 
?> 

See: readdir()

2

Utilizzando uno scandir o dir rende questo problema banale. Per ottenere tutti i file in una directory, tranne i file speciali . e .. in un array con indici a partire da 0, si può combinare scandir con array_diff e array_merge:

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

Ecco un metodo che utilizza la classe SPL DirectoryIterator:

<?php 

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

?> 
3

ancora più facile di readdir(), utilizzare glob:

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

più informazioni su glob

+1

Troppo sovraccarico con glob – RobertPitt

1

appena estendendosi sul post di Enrico, ci sono anche alcuni controlli/modifiche che devi fare.

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; 
    } 
} 

E l'utilizzo in questo modo:

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

questo modo si ottiene una lista in questo modo:

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

Hoep questo aiuta.

+1

Perché non utilizzare semplicemente RecursiveDirectoryIterator/DirectoryIterator ...? – ircmaxell

+0

Ci crediate o meno, ma alcune persone usano ancora PHP4.x – RobertPitt