PHP Force Download Causing 0 Byte Files(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 字节文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:PHP 强制下载导致 0 字节文件


基础教程推荐
- 在PHP中根据W3C规范Unicode 2022-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 如何替换eregi() 2022-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01