tags:

views:

51

answers:

4

hi, 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 "." ?

+5  A: 

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.

Sagi
haha. very cool, thank you sir!
sasori
+2  A: 
<?php
   if($handle = opendir($dir)){
       while($file = readdir($handle)){
          if(is_dir($file) && $file !== '.' && $file !== '..'){
             echo "<a href=\"$file\">$file</a><br />";
            }
       }
?>
code_burgar
thank you sir, nice alternative
sasori
+2  A: 

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;
    }
deceze
ah.thank you sir
sasori
+2  A: 

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.

Gordon
thanks for this too :)
sasori