Home  >  Article  >  Backend Development  >  PHP directory recursive traversal program_PHP tutorial

PHP directory recursive traversal program_PHP tutorial

WBOY
WBOYOriginal
2016-07-20 11:10:10732browse

A directory search program written by a friend can find the specified directory or file based on the directory name entered by the user. It also supports locking the directory. Friends in need can refer to it.

The code is as follows Copy code

class Finder{
private $key ;
private $result;
private $previewLen = 50;
private $file_type = array('html','php','htm','txt');

function __construct($key){
$this->key = $key;
}

function find($folder){
$this->result = array();

if(is_array($folder)){
foreach($folder as $f){
$this->_find_in_folder($f);
}
}else {
$this->_find_in_folder($folder, true);
}

return $this->result;
}

function _find_in_folder($folder ,$bSub=false){
foreach(glob($folder.DIRECTORY_SEPARATOR.'*') as $f){
if (is_file($f)){
$extend =explode(". " , $f);
$type = strtolower(end($extend));
if(in_array($type,$this->file_type)){
$fd = file_get_contents($f );
$pos = strpos($fd,$this->key);
if($pos!==false){
$end = $pre = '...';
$pos -= floor($this->previewLen/2);
if($pos<0){
$pre = '';
$pos = 0;
}

$findata = substr($fd,$pos,$this->previewLen);
$findata = str_replace($this->key,''.$this->key.'',$findata);
$this->result[] = array('path'=>$f,'preview' =>$pre.$findata.$end);
}
}
continue;
}

if($bSub && is_dir($f)){
$this->_find_in_folder($f,true);
}
}
}

}

$cur_path = dirname(__FILE__);
if(isset($_GET['a'])){
$key = $_POST['key'];
if(!$key) die('Keyword cannot be empty');

$cf = new Finder($key);

$in_folder = array();
$limit_folder = $_POST['limit_folder'];
if($limit_folder== 1){
if(!isset($_POST['folder']) || !$_POST['folder']) die('Limited directory cannot be empty');
$in_folder = $_POST[ 'folder'];
$ret = $cf->find($in_folder);
}else{
$ret = $cf->find($cur_path);
}

echo "Search [$key] results:
";
if(!$ret) die('none');
foreach($ret as $p=> ;$f){
echo "$p. t$f[path] => $f[preview]
n";
}
exit();
}

$folder = array();
function readFolder($path){
global $folder;
$folder[] = $path;
foreach(glob($ path.DIRECTORY_SEPARATOR.'*') as $f){
if (is_dir($f)) {
readFolder($f);
}
}
}

readFolder($cur_path);
$folder_op = array();
foreach($folder as $path){
$folder_op[] = "


Search for keywords:

Search for directories:

Whether to limit the directory selected above:YesNo

=


www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/444740.htmlTechArticleA directory search program written by a friend, which can find the specified directory or file based on the directory name entered by the user. , and also supports locking directories. Friends in need can refer to this...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn