您需要在 PHP 中添加什么代码才能在访问链接时自动让浏览器将文件下载到本地计算机?

我特别想到的功能类似于下载网站的功能,一旦您单击软件名称,就会提示用户将文件保存到磁盘?

有帮助吗?

解决方案

在输出文件之前发送以下标头:

header("Content-Disposition: attachment; filename=\"" . basename($File) . "\"");
header("Content-Type: application/octet-stream");
header("Content-Length: " . filesize($File));
header("Connection: close");

@格罗姆: :关于“application/octet-stream”MIME 类型很有趣。我没有意识到这一点,一直只使用“应用程序/强制下载”:)

其他提示

这是发回 pdf 的示例。

header('Content-type: application/pdf');
header('Content-Disposition: attachment; filename="' . basename($filename) . '"');
header('Content-Transfer-Encoding: binary');
readfile($filename);

@斯威什 我没有发现 application/force-download 内容类型可以做任何不同的事情(在 IE 和 Firefox 中测试)。有没有理由不发回实际的 MIME 类型?

PHP手册中也有 海莉·沃森 发布:

如果您希望强制下载并保存文件,而不是呈现文件,请记住没有“application/force-download”这样的 MIME 类型。在这种情况下使用的正确类型是“application/octet-stream”,使用其他任何类型仅依赖于这样一个事实:客户端应该忽略无法识别的 MIME 类型并使用“application/octet-stream”(参考:RFC 2046 第 4.1.4 和 4.5.1 节)。

还根据 互联网号码分配机构 没有注册的应用程序/强制下载类型。

一个干净的例子。

<?php
    header('Content-Type: application/download');
    header('Content-Disposition: attachment; filename="example.txt"');
    header("Content-Length: " . filesize("example.txt"));

    $fp = fopen("example.txt", "r");
    fpassthru($fp);
    fclose($fp);
?>

我的代码适用于 txt、doc、docx、pdf、ppt、pptx、jpg、png、zip 扩展名,我认为最好明确使用实际的 MIME 类型。

$file_name = "a.txt";

// extracting the extension:
$ext = substr($file_name, strpos($file_name,'.')+1);

header('Content-disposition: attachment; filename='.$file_name);

if(strtolower($ext) == "txt")
{
    header('Content-type: text/plain'); // works for txt only
}
else
{
    header('Content-type: application/'.$ext); // works for all extensions except txt
}
readfile($decrypted_file_path);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top