php 目录递归遍历程序

一个朋友写的一款目录查找程序,可以根据用户输入的目录名称查到到指定目录或文件,同时还支持锁定目录,有需要的朋友可以参考一下,代码如下:

  1. <?php
  2. class Finder{
  3. private $key;
  4. private $result;
  5. private $previewLen = 50;
  6. private $file_type = array('html','php','htm','txt');
  7. function __construct($key){
  8. $this->key = $key;
  9. }
  10. function find($folder){
  11. $this->result = array();
  12. if(is_array($folder)){
  13. foreach($folder as $f){
  14. $this->_find_in_folder($f);
  15. }
  16. }else{
  17. $this->_find_in_folder($folder, true);
  18. }
  19. return $this->result;
  20. }
  21. function _find_in_folder($folder,$bSub=false){
  22. foreach(glob($folder.DIRECTORY_SEPARATOR.'*') as $f){
  23. if (is_file($f)){
  24. $extend =explode("." , $f);
  25. $type = strtolower(end($extend));
  26. if(in_array($type,$this->file_type)){
  27. $fd = file_get_contents($f);
  28. $pos = strpos($fd,$this->key);
  29. if($pos!==false){
  30. $end = $pre = '...';
  31. $pos -= floor($this->previewLen/2);
  32. if($pos<0){
  33. $pre = '';
  34. $pos = 0;
  35. }
  36. $findata = substr($fd,$pos,$this->previewLen);
  37. $findata = str_replace($this->key,'<span >'.$this->key.'</span>',$findata);
  38. $this->result[] = array('path'=>$f,'preview'=>$pre.$findata.$end);
  39. }
  40. }
  41. continue;
  42. }
  43. if($bSub && is_dir($f)){
  44. $this->_find_in_folder($f,true);
  45. }
  46. }
  47. }
  48. }
  49. $cur_path = dirname(__FILE__);
  50. if(isset($_GET['a'])){
  51. $key = $_POST['key'];
  52. if(!$key) die('关键字不能为空');
  53. $cf = new Finder($key);
  54. $in_folder = array();
  55. $limit_folder = $_POST['limit_folder'];
  56. if($limit_folder==1){
  57. if(!isset($_POST['folder']) || !$_POST['folder']) die('限定目录不能为空');
  58. $in_folder = $_POST['folder'];
  59. $ret = $cf->find($in_folder);
  60. }else{
  61. $ret = $cf->find($cur_path);
  62. }
  63. echo "搜索[$key]结果:<br />";
  64. if(!$ret) die('无');
  65. foreach($ret as $p=>$f){
  66. echo "$p. t$f[path] => $f[preview] <br />n";
  67. }
  68. exit();
  69. }
  70. $folder = array();
  71. function readFolder($path){
  72. global $folder;
  73. $folder[] = $path;
  74. foreach(glob($path.DIRECTORY_SEPARATOR.'*') as $f){
  75. if (is_dir($f)) {
  76. readFolder($f);
  77. }
  78. }
  79. }
  80. readFolder($cur_path);
  81. $folder_op = array();
  82. foreach($folder as $path){
  83. $folder_op[] = "<option value="$path">$path</option>";
  84. }//开源代码phpfensi.com
  85. $folder_op = implode($folder_op);
  86. ?>
  87. <form action="?a=do" method="post">
  88. 搜索关键字:<input type="text" name="key" value=""><br />
  89. 搜索目录:<select name="folder[]" multiple="true"><?php echo $folder_op ?></select><br />
  90. 是否限定以上选择的目录:<input type="radio" name="limit_folder" value="1" />是 <input type="radio" name="limit_folder" value="0" checked="true" />否
  91. <input type="submit" value="搜索" />
  92. </form>