1

我已经编写了一个从服务器下载 pdf 文件的代码,但是代码不起作用,我什至看不到错误这是我正在使用的代码。

// place this code inside a php file and call it f.e. "download.php"
$path = $_SERVER['DOCUMENT_ROOT']."/product_images/"; // change the path to fit your     websites document structure
fullPath = $path.$_REQUEST['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>
?>

我正在从数据库中获取文件,这是我在我的网站上使用的下载链接

<div style="padding-left:320px; padding-top:5px;"><a href="<?php echo URL ?>download.php?download_file=<?php echo $prod_details['specification_pdf']?>">
<img src="<?php       echo URL ?>images/download_pdf.png" /></a></div>
</div>

谁能帮我解决这个问题

4

1 回答 1

6

正如@lasar 在第 2 行中缺少 $ 可能是问题所在。我调整(并测试)你的代码更安全(见基本名称)和直接(见 readfile):

<?php
$path = $_SERVER['DOCUMENT_ROOT']."/product_images/"; // change the path to fit your     websites document structure
$fullPath = $path.basename($_REQUEST['download_file']);

if (is_readable ($fullPath)) {
$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
readfile($fullPath);
exit;
} else {
        die("Invalid request");
}
// 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>

添加

  • 有关下载文件的标头的详细说明,请参见readfile 手册页
  • 记住由于它的性质 PHP 众所周知会损坏二进制文件下载,请记住将<?php始终保留在第一行并避免关闭标记?>在仅限 PHP 的文件中
于 2012-11-26T18:30:05.987 回答