【问题标题】:How to start download of file? [duplicate]如何开始下载文件? [复制]
【发布时间】:2011-08-06 02:00:09
【问题描述】:

可能重复:
Forcing to download a file using PHP

所以我在卖东西,我希望在用户访问感谢页面时开始下载文件。

文件的位置保存在$install,现在用户访问thanks.php,如何自动启动文件下载?

谢谢。

【问题讨论】:

  • 也许打开新窗口,位置 = $install
  • @experimentX nope..这不会是一次完美的体验。
  • 意思是……好吧,你打算控制下载吗??
  • 已经问过很多次了,比如这里stackoverflow.com/questions/1465573/…

标签: php file download


【解决方案1】:

JavaScript 重定向的替代方法是在 HTML 中使用 meta refresh 标记。即使禁用 javascript 也能正常工作。

【讨论】:

  • "refresh" 也可以用作 HTTP 标头。
【解决方案2】:
<?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>
?>

【讨论】:

    【解决方案3】:

    您想要做的大部分事情实际上都将在 Javascript 中完成。

    您的 PHP 代码将提供感谢页面,加载后,您需要将页面中隐藏的 iFrame 定向到提供文件作为下载的页面,使用以下标题:

    header("Content-Type: application/octet-stream");
    header("Content-Disposition: attachment; filename=yourfile.txt");
    readfile($pathToFile);
    

    【讨论】:

    • Javascript?为什么? locationredirect 标头有什么问题?为什么他需要使用“隐藏的 iframe”?
    • @binaryLV 因为我想他希望人们看到阅读thanks.php。如果您使用重定向,他们将永远看不到该页面。
    • 为什么不呢?打开“thanks.php”页面并发送“刷新”标题(不是“重定向”,正如我之前写的)。有什么问题?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-06
    • 2013-05-16
    • 2011-06-23
    • 2019-02-07
    • 2020-12-01
    • 1970-01-01
    相关资源
    最近更新 更多