Javascript 递归搜索子目录,忽略PHP目录
我使用AJAX和文本输入将搜索字符串发送到我当前的PHP文件,该脚本在目录中搜索文件和文件夹,但不搜索子文件夹。我想要的是只搜索目录和子目录中的文件,然后列出它们。结构如下:Javascript 递归搜索子目录,忽略PHP目录,javascript,php,ajax,search,Javascript,Php,Ajax,Search,我使用AJAX和文本输入将搜索字符串发送到我当前的PHP文件,该脚本在目录中搜索文件和文件夹,但不搜索子文件夹。我想要的是只搜索目录和子目录中的文件,然后列出它们。结构如下: Corecube -Categories --Movies ---File 1 ---File 2 ---File 3 --Music ---File 1 ---File 2 ---File 3 --Pictures ---File 1 ---File 2 ---File 3 -MainCategories --Code
Corecube
-Categories
--Movies
---File 1
---File 2
---File 3
--Music
---File 1
---File 2
---File 3
--Pictures
---File 1
---File 2
---File 3
-MainCategories
--Code
---File 1
---File 2
---File 3
--Gifs
---File 1
---File 2
---File 3
然后搜索在“Corecube”的父目录中进行,但只从每个子目录中吐出文件名,而不吐出实际目录。我尝试了当前脚本的几次迭代,但每次都失败了
<?php
$dir = "../corecube";
$key = $_GET['key'];
// Open a known directory, and proceed to read its contents
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
if($file == $key){
echo('<a href="'.$dir . $file.'">'. $file .'</a>'."\n");
}
}
closedir($dh);
}
}
?>
更新的代码格式:
您需要搜索嵌套文件夹中的文件
试试这个
<?php
function matchFile($filename, $path, $key)
{
if(preg_match("/$key/i",$filename))
{
echo('<a href="'.$path.'">'. $filename .'</a>'."<br>"); //use regex than casual '==' for flexible search
}
}
function getListDir($dir, $key)
{
if(strlen($key)<2) die("insert min 2 length string"); //for avoid return/display bunch of list file
if(is_dir($dir))
{
if ($dh = opendir($dir))
{
while (($file = readdir($dh)) !== false)
{
$newItem="$dir/$file";
if($file=='.' || $file=="..")
{
continue;
}
elseif(is_dir("$newItem"))
{
getListDir("$newItem", $key);
}
elseif(is_file("$newItem"))
{
matchFile($file, $newItem, $key);
}
else
{
//do nothing
}
}
}
else
{
die ("cant open folder: $folder");
}
}
}
//run script
$initialFolder="initialfolder"; // change this into "../corecube"
$key = (isset($_GET["key"]))?$_GET['key']:NULL;
getListDir($initialFolder, $key);
?>
这就是为什么该脚本被否决的原因。从android应用程序发布可以更改代码格式。现在我已经修好了