帮助理解这个PHP代码下载文件


Help understand this PHP code download file

我想下载一个位于http://confluence.rogersdigitalmedia.com/exportword?pageId=1114407.如何修改以下代码以从该URL下载文件??

有人能解释一下这个代码在当前状态下是做什么的吗?它从目录中下载了什么文件?

<?php
// place this code inside a php file and call it f.e. "download.php"
$path = $_SERVER['DOCUMENT_ROOT']."/path2file/"; // change the path to fit your websites document structure
$fullPath = $path.$_GET['download_file'];
if ($fd = fopen ($fullPath, "r")) {
    $fsize = filesize($fullPath);
    $path_parts = pathinfo($fullPath);
    $ext = strtolower($path_parts["extension"]);
    switch ($ext) {
        case "pdf":
        header("Content-type: application/pdf"); // add here more headers for diff. extensions
        header("Content-Disposition: attachment; filename='"".$path_parts["basename"]."'""); // use 'attachment' to force a download
        break;
        default;
        header("Content-type: application/octet-stream");
        header("Content-Disposition: filename='"".$path_parts["basename"]."'"");
    }
    header("Content-length: $fsize");
    header("Cache-control: private"); //use this to open files directly
    while(!feof($fd)) {
        $buffer = fread($fd, 2048);
        echo $buffer;
    }
}
fclose ($fd);
exit;
// example: place this kind of link into the document where the file download is offered:
// <a href="download.php?download_file=some_file.pdf">Download here</a>
?>

这段代码应该通过PHP下载文件。通常,它用于隐藏包含下载的目录,或者下载由于文件在web根目录之外而无法访问的文件。这种脚本的另一个用途是为授权用户提供下载,您必须在脚本中进行身份验证检查。

如果文件有PDF扩展名,则下载与PDF mimetype一样提供,因此浏览器可以在PDF查看器中打开它。其他文件作为二进制文件提供,可以保存。

不要"按原样"使用此脚本。它包含一个巨大的安全漏洞,允许攻击者查看系统上的任意文件(路径遍历)。替换行:

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

以下内容使其更加安全:

$fullPath = $path . basename($_GET['download_file']);

更好的是:通过允许文件名位于允许的字符集中并拒绝其他无效文件名来实现白名单。


下载外部文件就像以下cURL:的例子一样简单

<?php
$ch = curl_init("http://www.example.com/");
$fp = fopen("example_homepage.txt", "w");
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);
?>

由于我对您下载的URL一无所知,我将保留PHP示例中的原始URL和文件名。

这段代码是您放在自己的服务器上的,允许人们通过PHP下载文件。通常你会在那里添加一些身份验证代码,这样PHP就可以在下载之前接受/拒绝用户。