php文件搜索问题 - 不返回文件的完整路径

时间:2013-07-04 13:27:38

标签: php file search

此脚本将在我的服务器中搜索以特定字符串开头的文件,然后返回下载链接。搜索查询由“f”GET值定义。

现在假设我的服务器上有以下文件:

  

/ folder / example文件编号one.zip   / folder / example文件号two.zip   / folder / example文件号为three.zip

如果我搜索“示例文件”,则脚本将返回3个结果但是每个下载链接将是“/ folder / example file”而不是FULL文件名(/ folder / example文件号XXX.zip)。

这也会在脚本末尾创建filesize()函数的错误,因为filesize()会查找“/ folder / example file”的大小,而不是使用完整的文件名

你能帮我解决这个问题吗?

$request = $_GET['f'];
$adr = $_SERVER['QUERY_STRING'];
$decode = rawurldecode(substr($adr, 2));

echo "Searching for $decode";

// finding the file on the server
$root = $_SERVER['DOCUMENT_ROOT'];
$search = preg_quote(utf8_decode($decode));

function rsearch($folder, $pattern) {
    $dir = new RecursiveDirectoryIterator($folder);
    $ite = new RecursiveIteratorIterator($dir);
    $files = new RegexIterator($ite, $pattern, RegexIterator::GET_MATCH);
    $fileList = array();
    foreach ($files as $file) {
        $fileList = array_merge($fileList, $file);
    }
    return $fileList;
}
$resultatss = rsearch($root, '/.*\/'.$search.'/');

foreach ($resultatss as $resultat) {
    $downloadlink = str_replace("$root/", "", $resultat);
    $pos = strrpos($downloadlink, '/') + 1;
    $encodedownloadlink = substr($downloadlink, 0, $pos) . rawurlencode(substr($downloadlink, $pos));

    if (!empty($downloadlink)) {
        echo "download link = http://www.mydomain.com/$encodedownloadlink";
        $taillekb = filesize($downloadlink) / 1024;
        echo "<br>Size: $taillekb KB<br>";
    } else {
        echo "File not found";
    }

 }

1 个答案:

答案 0 :(得分:0)

我不熟悉RecursiveDirectoryIterator功能,所以我决定检查一下。整洁的东西!我写了以下内容,它似乎做你想做的事:

方法#1 ......

$path = $_SERVER['DOCUMENT_ROOT'];
$search = rawurldecode($_GET['f']);

$it = new RecursiveDirectoryIterator( $path );
foreach (new RecursiveIteratorIterator($it) as $file){
    $pathfile = str_replace($path,'',$file);
    if (strpos($pathfile, $search) !== false) {
        echo 'file = '. basename($file) .'<br>';
        echo 'link = http://www.mydomain.com'. $pathfile .'<br>';
        echo 'size = '. round(filesize($file)/1024,2) .' KB<br><br>';
    }
}

您通过http://www.mydomain.com/search.php?f=whatever运行...假设您将脚本命名为search.php,这将找到包含whatever字样的任何文件。

方法#2 ......

如果你想把它拆开(把搜索放在一个函数中),这就是它的样子:

function rsearch($path, $search) {
    $files = array();
    $it = new RecursiveDirectoryIterator( $path );
    foreach (new RecursiveIteratorIterator($it) as $file){
        if (strpos($file, $search) !== false) $files[] = $file;
    }
    return $files;
}

$path = $_SERVER['DOCUMENT_ROOT'];
$search = rawurldecode($_GET['f']);

$files = rsearch($path, $search);

foreach ($files as $file) {
    $pathfile = str_replace($path,'',$file);
    if (strpos($pathfile, $search) !== false) {
        echo 'file = '. basename($file) .'<br>';
        echo 'link = http://www.mydomain.com'. $pathfile .'<br>';
        echo 'size = '. round(filesize($file)/1024,2) .' KB<br><br>';
    }
}