列出所有目录(在硬盘上)及其文件夹和文件

时间:2016-01-08 17:44:17

标签: php windows directory

有没有办法可以在我的电脑上阅读整个文件系统?我试图列出W:目录中的所有文件,但代码不起作用。

<?php
 $fso = new COM('Scripting.FileSystemObject'); 
    $D = $fso->Drives; 
    $type = array("Unknown","Removable","Fixed","Network","CD-ROM","RAM Disk"); 
    foreach($D as $d ){ 
       $dO = $fso->GetDrive($d); 
       $s = ""; 
       if($dO->DriveType == 3){ 
           $n = $dO->Sharename; 
       }else if($dO->IsReady){ 
           $n = $dO->VolumeName; 
           $s = file_size($dO->FreeSpace) . " free of: " . file_size($dO->TotalSize); 
       }else{ 
           $n = "[Drive not ready]"; 
       } 
   echo "Drive " . $dO->DriveLetter . ": - " . $type[$dO->DriveType] . " - " . $n . " - " . $s . "<br>"; 
   $dir = $dO->DriveLetter;

   if (is_dir($dir.':\\')){ // NEVER ENTERS THE IF BLOCK
    if ($dh = opendir($dir)){
      while (($file = readdir($dh)) !== false){
        echo "filename:" . $file . "<br>";
      }
      closedir($dh);
    }
  }

    } 

      function file_size($size) 
      { 
      $filesizename = array(" Bytes", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB"); 
      return $size ? round($size/pow(1024, ($i = floor(log($size, 1024)))), 2) . $filesizename[$i] : '0 Bytes'; 
      } 


?> 

在上面的代码is_dir中,调用始终失败。这可能是什么原因?阅读Windows文件系统的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

试试这个http://php.net/manual/en/class.recursivedirectoryiterator.php

<?php

$path = realpath('/etc');

$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST);
foreach($objects as $name => $object){
    echo "$name\n";
}