edoceo

The function below will return a sorted array of directories & files in the requested directory. No hidden (/^./) files are listed. Copy and paste away.

// @return array of names
function directory_listing($d)
{
  $dl = array();
  if ($hd = opendir($d)) {
    while ($sz = readdir($hd)) {
      if (preg_match("/^\./",$sz)==0) {
        $dl[] = $sz;
      }
    }
    closedir($hd);
  }
  asort($dl);
  return $dl;
}

Here is the same routine with PHP SPL objects. The list returned contains objects that represent each of the files.

// @return array of directory entry objects (files/dirs)
function directory_listing($d)
{
  $di = new DirectoryIterator($d);
  $dl = array();
  foreach ($di as $de) {
    if ($de->isDot()) {
      continue;
    }
    //echo $de->getFilename() . "\t";
    //echo $de->getSize() . "\t";
    //echo $de->getOwner() . "\t";
    //echo $de->getMTime() . "\n";
    $dl[$de->getFilename()] = $de;
  }
  ksort($dl);
  return $dl;

Either one can be used as follows:

$list = directory_listing('/opt/foo/bar');

Loading Comments from Disqus...