PHP 强制下载导致 0 字节文件 [英] PHP Force Download Causing 0 Byte Files

查看:48
本文介绍了PHP 强制下载导致 0 字节文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to force download files from my web server using PHP. I'm not a pro in PHP but I just can't seem to get around the problem of files downloading in 0 bytes in size.

代码:

$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);

有人可以帮忙吗?谢谢.

Can anybody help? Thanks.

推荐答案

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

You're not checking that the file exists. Try using this:

$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";
}

看看你得到了什么.

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

You should also note that this forces a download as an octet stream, a plain binary file. Some browsers will struggle to understand the exact type of the file. If, for example, you send a GIF with a header of Content-Type: application/octet-stream, then the browser may not treat it like a GIF image. You should add in specific checks to determine what the content type of the file is, and send an appropriate Content-Type header.

这篇关于PHP 强制下载导致 0 字节文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆