开发者

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 redi开发者_JAVA百科rected one level up the directories.. can someone tell me how to remove those ".." and "." ?


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.


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.


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;
    }


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜