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行目で$を欠落していると言うように、問題になる可能性があります。私はあなたのコードをより安全で(basenameを参照)そして直接(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を常に1行目に保持し、タグを閉じるのを避けるように注意してください
于 2012-11-26T18:30:05.987 に答える