IT技术博客大学习 共学习 共进步

php 返回目录下的所有文件名/文件夹类

Everyday NetLog 2010-03-24 23:37:49 浏览 4,302 次
PHP读取目录树下的文件及目录方法。
这里为了便于演示,直接列出来了,其中可以返回数组之类的,根据需要另作改动。
代码如下,可以直接Copy测试。
 
  1. <?php   
  2.  main();   
  3.   
  4.  function main(){   
  5.  //Set Variables   
  6.  $testDirName = "./zhoz/";   
  7.  $fileListArray = array();   
  8.  $dirListArray = array();   
  9.   
  10. $aDirectory = new DirReader($testDirName);   
  11.   
  12. // Store File List in Array   
  13. $fileListArray = $aDirectory->getFileList();   
  14. $dirListArray = $aDirectory->getDirList();   
  15.   
  16. echo "<html><body>\n";   
  17. echo "<pre>\n";   
  18.   
  19.   
  20. echo "Reading Directory: ".  $aDirectory->getDirPath() ."\n";   
  21. echo "Current Directory: "getcwd() ."\n";   
  22.   
  23. echo "-- Files in Directory --\n";   
  24. foreach ($fileListArray as $filename) {   
  25.     echo "File: $filename\n";   
  26. }   
  27.   
  28. echo "\n-- Sub Directories --\n";   
  29. foreach ($dirListArray as $filename){   
  30.     echo "Sub dir: $filename\n";   
  31. }   
  32. echo "</pre></body></html>\n";   
  33. }   
  34.   
  35. class DirReader{   
  36.   private $dh;   
  37.   private $basedir;   
  38.   private $fileNameArray=array();   
  39.   private $dirNameArray=array();   
  40.   
  41.   function __construct($dirname){   
  42.     $this->basedir = $dirname;   
  43.     $this->dh = dir($dirnameor die($php_errormsg);   
  44.     $this->parseDirectory();   
  45.   }   
  46.   
  47.   function parseDirectory(){   
  48.     $filename = "";   
  49.     while (false !== ($filename = $this->dh->read())){   
  50.       $fullpath = $this->basedir . '/' . $filename;   
  51.       if (is_file($fullpath)){   
  52.         array_push($this->fileNameArray, $filename);   
  53.       }else{   
  54.         array_push($this->dirNameArray, $filename);   
  55.       }   
  56.     }   
  57.   }   
  58.   
  59.   
  60.   // Get all the files in the directory   
  61.   function getFileList(){   
  62.     return $this->fileNameArray;   
  63.   }   
  64.   
  65.   // Get all the sub directories in the directory   
  66.   function getDirList(){   
  67.     return $this->dirNameArray;   
  68.   }   
  69.   
  70.   function getDirPath(){   
  71.     return $this->dh->path;   
  72.   }   
  73. }   

建议继续学习

  1. Bash 小技巧:给目录加上书签,快速切换目录 (阅读 7,946)
  2. 查找当前目录的重复文件 (阅读 3,822)
  3. linux文件目录操作总结 (阅读 3,601)
  4. bash遍历目录 (阅读 3,521)
  5. apache配置(如何禁止列出目录内容) (阅读 3,341)
  6. MySql重启命令与数据库安装目录 (阅读 3,262)
  7. 递归创建目录的一个函数 (阅读 3,122)
  8. FREEBSD 建目录上限 (阅读 3,101)
  9. 记一个php函数dirname (阅读 2,941)
  10. Linux(CentOS)下更改/转移MySQL数据库目录 (阅读 2,921)