简体   繁体   中英

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

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM