我已经编写了一个从服务器下载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>
任何人都可以帮我解决这个问题
答案 0 :(得分:5)
据说@lasar在第2行中缺少$可能是问题所在。 我调整(并测试)你的代码更安全(参见basename)和direct(参见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>
ADD