强制直接链接文件下载

时间:2013-07-09 09:15:50

标签: php download

有没有办法提供到文件的直接链接并强制浏览器使用PHP下载它?

E.g http://www.website.com/directory/file.jpg

我们在这里处理大量文件,特别是Chrome似乎在渲染图像方面存在问题,因此当直接访问文件时,所有用户看到的都是空白屏幕。即使他们仍然可以在空白屏幕上右键单击并下载文件,但这很令人困惑。

我们曾经从PHP输出文件,但我们遇到了内存问题,所以改为提供直接链接。文件高达约5GB,并非所有图像。我们有拉链,PDF,PSD等。

目前,通过PHP脚本请求文件,该脚本接受文件的ID并获取其URL。然后,PHP脚本将用户重定向到该文件的完整URL。

我们如何确保强制下载,并且我们不会遇到较大文件的内存问题?

谢谢

3 个答案:

答案 0 :(得分:3)

只需使用X-Sendfile,但您需要先使用XSendFilePath

进行配置
if (file_exists($file)) {
    header("X-Sendfile: $file");
    header("Content-Type: application/octet-stream");
    header(sprintf("Content-Disposition: attachment; filename=\"%s\"", basename($file)));
    exit();
}

注意* 请确保在验证并提供文件之前正确转义$file

XSendFilePath仅适用于其他服务器的Apache,请参阅:Caching HTTP responses when they are dynamically created by PHP

答案 1 :(得分:0)

您需要设置强制下载headers

        $file = 'upload_directory_path/'.$image_name;

        if (file_exists($file)) {
            header('Content-Description: File Transfer');
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename='.basename($file));
            header('Content-Transfer-Encoding: binary');
            header('Expires: 0');
            header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
            header('Pragma: public');
            header('Content-Length: ' . filesize($file));
            ob_clean();
            flush();
            readfile($file);
            exit;
        }

答案 2 :(得分:0)

<?php 
//file path
$file = 'monkey.gif';

if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename($file));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    ob_clean();
    flush();
    readfile($file);
    exit;
}