< All PHP topicsPHP (1)Perl (3)Java (4)

File I/O

Using files and filesystems

PHP:

Handling server-side files.

Get Directory Listing

Last updated at 03:36 PM on Monday 30th July, 2007 by Isaac Turner


<?
$directory 
'path/to/directory';
$files = array();

// Try to open directory
if($handle opendir($directory))
{
  
// Read in filenames one at a time
  
while(($file readdir($handle)) !== false)
  {
    
// Do not add unix 'files' . (current directory) and .. (parent directory) 
    
if($file !== '.' && $file !== '..')
      
$files[] = $file;
  }

  
// Close
  
closedir($handle);
}
else
{
  echo 
'Error opening directory ' $directory;
}
?>

It's important that the loop

while(($file = readdir($handle)) !== false)

uses the !== comparator instead of just != so files with names equivalent to false ('0', 'false') are added

Comments (11)