sasori
sasori

Reputation: 5463

PHP list directories and remove .. and

I created a script that list the directories in the current directory

<?php
   $dir = getcwd(); 
   if($handle = opendir($dir)){
       while($file = readdir($handle)){
          if(is_dir($file)){
             echo "<a href=\"$file\">$file</a><br />";
            }
       }
?>

but the problem is, I am seeing this ".." and "." right above the directory listings, when someone clicks it, they get redirected one level up the directories.. can someone tell me how to remove those ".." and "." ?

Upvotes: 1

Views: 3536

Answers (4)

code_burgar
code_burgar

Reputation: 12323

<?php
   if($handle = opendir($dir)){
       while($file = readdir($handle)){
          if(is_dir($file) && $file !== '.' && $file !== '..'){
             echo "<a href=\"$file\">$file</a><br />";
            }
       }
  }
?>

Upvotes: 2

Gordon
Gordon

Reputation: 317119

Or use glob:

foreach(glob('/path/*.*') as $file) {
    printf('<a href="%s">%s</a><br/>', $file, $file);
}

If your files don't follow the filename dot extension pattern, use

array_filter(glob('/path/*'), 'is_file')

to get an array of (non-hidden) filenames only.

Upvotes: 3

Sagi
Sagi

Reputation: 8011

If you use opendir/readdir/closedir functions, you have to check manually:

<?php
if ($handle = opendir($dir)) {
    while ($file = readdir($handle)) {
      if ($file === '.' || $file === '..' || !is_dir($file)) continue;
      echo "<a href=\"$file\">$file</a><br />";
    }
}
?>

If you want to use DirectoryIterator, there is isDot() method:

<?php
$iterator = new DirectoryIterator($dir);
foreach ($iterator as $fileInfo) {
    if ($fileInfo->isDot() || !$fileInfo->isDir()) continue;
    $file = $fileinfo->getFilename();
    echo "<a href=\"$file\">$file</a><br />";
}
?>

Note: I think that continue can simplify this kind of loops by reducing indentation level.

Upvotes: 8

deceze
deceze

Reputation: 522402

Skips all hidden and "dot directories":

while($file = readdir($handle)){
    if (substr($file, 0, 1) == '.') {
        continue;
    }

Skips dot directories:

while($file = readdir($handle)){
    if ($file == '.' || $file == '..') {
        continue;
    }

Upvotes: 2

Related Questions