使用PHP强制下载文件提供空文件 [英] Force download file with PHP giving empty file

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

问题描述

最终目标是让用户下载.csv文件。现在我只是试图下载一个简单的文本文件:test.txt。这个文件中唯一的内容是test一词。

The end goal is for the user to download a .csv file. Right now I'm just testing trying to download a simple text file: test.txt. The only thing in this file is the word "test".

以下是files_to_download.php的HTML代码

Here is the HTML code for files_to_download.php

Test file: <a href='test.php?file=test.txt'>Test.txt</a>

test.php代码:

Code for test.php:

if(!(empty($_GET["file"])))
{
    $file_name = $_GET["file"];
    $path = "path/to/file";
    $fullPath = $path . $file_name;

    if(ini_get('zlib.output_compression'))
      ini_set('zlib.output_compression', 'Off');

    header("Cache-Control: public");
    header("Content-Description: File Transfer");
    header("Content-Disposition: inline; attachment; filename=\"$file_name\"");
    header("Content-Type: text/plain");
    header("Content-Transfer-Encoding: binary");
    readfile($fullPath);
}

我尝试过上述标题的变体,添加更多内容并删除其他标题。以上似乎是本网站推荐的最常见的。

I've tried variations of the headers above, adding more and removing others. The above seem to be the most common recommended on this site.

我也尝试更改

header("Content-Type: text/plain");

header("Content-Type: text/csv");

并获得相同的结果:空的.txt或.csv文件。

and get same results: empty .txt or .csv file.

当从服务器直接打开文件(文件浏览器)时,文件不为空。我检查了这些文件的权限,它们都是644,所以整个世界至少可以读取这些文件。目录是777。

The files are not empty when I open them directly (file browser) from the server. I've checked the permissions of the files and they're both 644, so the entire world can at least read the files. The directory is 777.

Apache服务器上有一个配置,我需要指定可能不是,或者我缺少上面的东西。

Is there a configuration on the Apache server I need to specify that may not be or am I missing something above.

感谢寻找!

推荐答案

在大多数情况下,路径错误

In most cases the path is wrong

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

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