0

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

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

/文件夹/示例文件编号一.zip /文件夹/示例文件编号二.zip /文件夹/示例文件编号三.zip

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

这也将在脚本末尾使用 filesize() 函数创建一个错误,因为 filesize() 将查找“/文件夹/示例文件”的大小而不是使用完整的文件名

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

$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";
    }

 }
4

1 回答 1

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>';
    }
}
于 2013-07-04T13:34:07.513 回答