Monday, 23 April 2007

PHP: Directory Listing

Here is a snipper I use to get the contents of a directory. I have many times searched the WEB -- and my files -- for similar functionality so I thought I might put it here to save me the the next searches. The PHP manual for opendir that contains similar code can be found here.

 * returns an associative array containing the file list of the $directory parameter
 * $fileList[$file_name]contains the size of the file or 0 if file_name is a irectory
function fileList($disrectory)
   $files = array();
   if (!is_dir($directory))
      return $files;

   if (false == ($d = @opendir($directory)))
     return NULL;

   while (false != ($f = readdir($d))) {
      $fullName = "$directory/$f";
      $files[$f] = is_file($fullName) ? filesize($fullName) : 0;

   return $files;

No comments :