php - 在 PHP 中使用 Header 作为下载链接

标签 php header http-headers

所以我的下载链接出现了这个问题。基本上我以前创建下载链接的方法是只有一个带有 method='link' 的表单按钮和作为文件链接的操作。这适用于 firefox 和其他但不适用于 safari。出于某种原因,当用户尝试从 safari 下载文件(excel 文件)时,它只会在浏览器上显示一堆 ascii 字符(我猜它试图使用浏览器读取它?)。好吧,我正在寻找另一种解决方案,似乎使用 header 是解决问题的方法。所以现在我正在尝试使用 method='post' 和 action='download.php' 创建一个表单按钮,其中有一个带有文件链接的隐藏字段。看起来像这样

function showDownloadWithHeader($link){
    echo "<form action='download.php' method='post' >";
    echo "<input class='downloadButton' type='submit' value='Download Report'>";
    echo "<input type='hidden' name='filename' value='$link'>";
    echo "</form>";
}

在 download.php 中,我只想要求用户下载文件。

<?php
    if($_POST['filename'] == '' || empty($_POST['filename'])){
        exit;
    }

    $filename = $_POST['filename']; //the file is 2 folder down. e.g. data/stack/bla.xlsx
    $file = $filename;
    $extension = end(explode('.', $filename));
    error_reporting(E_ALL);
    ini_set("display_errors",1);
//  echo $filename;
//  echo "<br/>";
//  echo $extension;
//  echo filesize($filename);
//  echo "<br/>";
    switch($extension){
        case 'xls':
            $mimeType = 'application/vnd.ms-excel';
            break;
        case 'xlsx':
            $mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
            break;
    }
//  echo $mimeType;
    header('Content-Description: File Transfer');
    header('Content-Type: ' . $mimeType);
    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($filename);
    exit;
?>

我在 php.net 上的 readfile() 函数下看到了这个解决方案,但它似乎对我不起作用。我在本地主机上执行此操作。

最佳答案

这样的东西很好用。

header("Pragma: public", true);
header("Expires: 0"); // set expiration time
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Disposition: attachment; filename=".basename($file));
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($file));
die(file_get_contents($file));

关于php - 在 PHP 中使用 Header 作为下载链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3479432/

相关文章:

php - 正则表达式匹配语法

javascript - 我的 Ajax PHP 代码无法正常工作

php - 如何使用 php 和 mysql 处理加密的私有(private)消息

php - Auth::check() 返回 false Laravel 5.4

php - 如何修复PHP中的“ header 已发送”错误

http - 'Access-Control-Allow-Origin: *' 的缺点?

css - 位置 :Fixed; Scaling Methods for Web Browsers

html - 如何让标签背景到达页面边缘

php - 如果在 WordPress 中修改自 header

angular - 预检响应中的 Access-Control-Allow-Headers 不允许请求 header 字段 Access-Control-Allow-Methods