PHP显示/下载webserver根目录之外的目录文件

Jop*_*per 1 html php directory

我已经下载并添加这个非常简单,一个文件,PHP网页文件浏览器系统(称为索引)到我的XAMPP服务器.

我的XAMMP服务器在我的C:驱动器上,但我希望Indexer在我的G:驱动器上显示一个目录.但是当我改变(我认为是)正确的配置变量时,它无法正常工作.

以下是我认为与该问题有关的代码:

// configuration  
$Root = realpath("G:/test");  
$AllowDownload = TRUE;  
$WebServerPath = dirname("G:/test");
Run Code Online (Sandbox Code Playgroud)

然后在代码中......

elseif ($AllowDownload) {  

        echo "<a href=\"http://".getenv("SERVER_NAME").$WebServerPath."/$rel_path".$item["filename"]."\">".$item["name"]."</a>";
    }
Run Code Online (Sandbox Code Playgroud)

这是发生了什么:该脚本正确地显示在G"测试"目录中的内容:驱动器,但是当我点击该文件名,来,因为PHP构建链接错误的链接断开下载/查看文件(我想).链接如下所示:http:// localhostg // [文件名].

你知道如何解决这个问题吗?

如果我更改配置变量以便显示相对子目录的内容,则此脚本可以正常工作.它还说$ Root变量可以位于webserver根目录之外.

此外,即使点击链接不起作用,右击并选择"目标另存为"让我保存/下载文件.

(随意询问您是否需要更多信息):)

Ist*_*ros 5

您的Web服务器无法查看DocRoot外部的文件,因此无法通过具有直接链接的浏览器来提供文件.您需要readfile()在正确设置标题的情况下将其内容打印到浏览器中.

要使其工作,您需要更改indexer.php中的配置:

// this way it works with accentuated letters in Windows
$Root = utf8_decode("G:\test"); // define the directory the index should be created for (can also be located outside the webserver root)

$AllowDownload = TRUE; // enclose file items with the anchor-tag (only makes sense when the files are in the webserver root)
// you need to place download.php in the same directory as indexer.php
$WebServerPath = dirname($_SERVER['SCRIPT_NAME']) . "/download.php?path="; // path where the indexed files can be accessed via a http URL (only required when $AllowDownload is TRUE)
Run Code Online (Sandbox Code Playgroud)

并且您必须download.phpindexer.php与此内容相同的目录中放置一个新文件:

<?php

// it must be the same as in indexer.php
$Root = utf8_decode("G:\test");

function checkFileIsInsideRootDirectory($path, $root_directory) {
    $realpath = realpath($path);

    if (!file_exists($realpath))
        die("File is not readable: " . $path);

    // detects insecure path with for example /../ in it
    if (strpos($realpath, $root_directory) === false || strpos($realpath, $root_directory) > 0)
        die("Download from outside of the specified root directory is not allowed!");
}

function forceDownload($path) {
    $realpath = realpath($path);

    if (!is_readable($realpath))
        die("File is not readable: " . $path);

    $savename = (basename($path));

    header("Pragmaes: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Cache-Control: private", false);
    header("Content-type: application/force-download");
    header("Content-Transfer-Encoding: Binary");
    header("Content-length: " . filesize($path));
    header("Content-disposition: attachment; filename=\"$savename\"");

    readfile("$path");
    exit;
}

if (!isset($_GET['path']))
    die("Path not specified!");

$fullPath = $Root . $_GET['path'];

checkFileIsInsideRootDirectory($fullPath, $Root);

forceDownload($fullPath);
Run Code Online (Sandbox Code Playgroud)