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

时间:2011-06-03 14:57:22

标签: php file download

我想下载位于http://confluence.rogersdigitalmedia.com/exportword?pageId=1114407的doc文件。如何修改以下代码以从该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>
?>

2 个答案:

答案 0 :(得分:2)

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

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

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

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

使用以下内容使其更安全:

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

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


下载外部文件就像遵循example of 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);
?>

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

答案 1 :(得分:0)

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