Articles
Image pour le titre du contenu

Ce document est aussi disponible en français fr 


It happens that one have to list files and folders in a specific folder, and this is exactly the goal of scandir. This function works on the local filesystem of the server.

It is really convenient to replace the famous loop including opendir(),  readdir()  and closedir(). It also adds the full path of every file. This way, one can rapidly create a full tree, and check if a file exists or not.

Example 1 - Fast lane to folder listing
<?php
   echo '<h1>Index of /</h1>';
   echo '<ul>';
   $dir = scandir('.');
   $files = count( $dir );
   for ( $i = 0; $i < $files; $i++ )
   {
       if ( is_file($dir[$i]) )
           echo "<li><a href=\"$dir[$i]\">$dir[$i]</a></li><br>";
 
 
       if ( is_dir($dir[$i]) )
           echo "<li><a href=\"$dir[$i]\"/>$dir[$i]/</a></li><br>";
   }
   echo '</ul>';
?>

Example 2 - Sorting files and folders
<?php
 
$files = scandir ( $myDir );
 
foreach( $files as $pos => $file ) {
 
   if( is_dir( $file ) ) {
 
       $dirs[] = $file ;
 
       unset( $files[$pos] ) ;
 
   }
 
}
 
?>
 

Limitations

  • Scandir() isn't recursive. So, you have to check if a file is a folder, then call scandir again.
  • Scandir() have no built-in filters. If you want only a few files, you'll have to make a loop anyway.
Keep in mind
  • scandir() is available since PHP 5.
  • scandir() return FALSE in case of error, of if there is nothing to list.

Commentaires

Vous pouvez ajouter votre commentaire!


Vous devez vous connecter pour commenter