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

查看:878
本文介绍了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图像。您应该添加特定检查以确定文件的内容类型,并发送适当的内容类型标题。

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天全站免登陆