PHP 强制下载导致 0 字节文件

标签 php download

我正在尝试使用 PHP 从我的 Web 服务器强制下载文件。 我不是 PHP 专家,但我似乎无法解决以 0 字节大小下载文件的问题。

代码:

$filename = "FILENAME...";

header("Content-type: $type");
header("Content-Disposition: attachment;filename=$filename");
header("Content-Transfer-Encoding: binary");
header('Pragma: no-cache');
header('Expires: 0');
set_time_limit(0);
readfile($file);

有人可以帮忙吗? 谢谢。

最佳答案

您没有检查文件是否存在。尝试使用这个:

$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, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    ob_clean();
    flush();
    readfile($file);
    exit;
}else
{
    echo "File does not exists";
}

看看你得到了什么。


您还应该注意,这会强制下载为八位字节流,一个普通的二进制文件。一些浏览器很难理解文件的确切类型。例如,如果您发送一个 header 为 Content-Type: application/octet-stream 的 GIF,则浏览器可能不会将其视为 GIF 图像。您应该添加特定检查以确定文件的内容类型,并发送适当的 Content-Type header 。

关于PHP 强制下载导致 0 字节文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4706073/

相关文章:

python - 从 URL 下载返回的 Zip 文件

javascript - 是否可以仅使用 JavaScript(客户端方法)在浏览器中针对可识别的 MIME 类型启动下载提示?

ruby - 如何在 ruby​​ 中快速下载大量网页?并行下载?

java - 安卓 : Download a single file in many parts

php - MySQL查询选择数据

javascript - 如何在 wordpress 前端使用 ajax 保存帖子和自定义字段值?

file - 我可以创建一个带有内容处置 : attachment? 的一次性 S3 链接吗

php - 将 $mysqli 设置为 OOP 的全局变量

PHP 开关语句

php - jquery将html写入变量