Show all of the Files in a Directory

The dir command can retrieve all of the files in a directory. In this example $dirEntries will be a member of the Directory Class. This class has the following methods: read, rewind, and close. It also has two properties: $dirEntries->handle and $dirEntries->path.

$path='/mystuff/pictures';
$dirEntries = dir($_SERVER['DOCUMENT_ROOT'].'$path);
while($entry = $dirEntries->read()) {
  echo $entry."<BR>"; //these will not be in order
}
$dirEntries->close();

This will show all of the files in your directory (folder) called mystuff/pictures. These will probably not be in alphabetical order. You could add each one to an array, sort the array , then print. You could also create an index by printing each one as a link:

$path='/mystuff/pictures';
$dirEntries = dir($_SERVER['DOCUMENT_ROOT'].$path);
$n=0;
while($entry = $dirEntries->read()) {
  $files[$n++]=$entry;
}
$dirEntries->close();
sort($files);
foreach($files as $id=>$data) {
  echo '<a href="'.$path.'/'.$data.'">'.$data.'</a><BR>';
}

INDEX, Read a file, Get all of the files in a directory, Write files
Next lesson: OOP: Object Oriented ProgrammingMAIN INDEX
EXAMPLES INDEX

Copyright © Zebra0.com
All rights reserved worldwide.

 
 

Get all of the files in a directory