编程语言
首页 > 编程语言> > php – xsendFile下载有0个字节

php – xsendFile下载有0个字节

作者:互联网

在LAMP堆栈上,我无法使xSendFile工作.问题是下载有0个字节.

为了确保我安装了xSendFile,我已将其添加到我的.htaccess文件中:

<IfModule mod_xsendfile.c>
  SetEnv MOD_mod_xsendfile 1
</IfModule>

(我无法使用apache_get_modules()进行测试,因为我将PHP作为fastCGI运行.)

然后我有以下PHP代码:

 if (1 != getenv('MOD_mod_xsendfile'))
    {
        echo 'mod_xsendfile is not installed';
    }
    else
    {
        $path = '/home/infar/';
        $file = 'hello.txt';
        if (file_exists($path.$file) && strlen($path.$file)>1)
        {
            if (true) // change to false to go around Yii
            {
                Yii::app()->request->xSendFile($path.$file,array(
                    'saveName'=> 'hello.txt',
                    'mimeType'=> 'plain/text',
                    'terminate'=> true,
                ));
            }
            else
            {
                //set proper Content-Type
                header('Content-Type: plain/text');
                //force download box with the filename hello.txt
                header('Content-Disposition: attachment;filename=hello.txt');
                header('X-Sendfile: $path.$file');
                exit;      
            }  
        }
        else
        {
            echo 'file not found at: '.$path.$file;
        }
    }

此代码按预期运行;我从中得出结论,必须安装和/或启用xSendFile.然后我用Yii xSendFile和普通的PHP运行这个脚本.在这两种情况下,下载窗口都会打开,但始终为0字节.

我没办法.我究竟做错了什么?

为了充分披露,这里是httpd.conf的相关部分:

<IfModule mod_xsendfile.c>
    XSendFile on
    XSendFilePath /home/infar
</IfModule>

编辑:

输出压缩已关闭:

ini_get("zlib.output_compression"); // returns "Off"

Chrome向我显示以下标题:

Cache-Control:no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Connection:Keep-Alive
Content-Disposition:attachment;filename=hello.txt
Content-Length:0
Content-Type:plain/text
Date:Sun, 23 Mar 2014 18:22:49 GMT
Expires:Thu, 19 Nov 1981 08:52:00 GMT
Keep-Alive:timeout=2, max=100
Pragma:no-cache
Server:Apache
X-Sendfile:/home/infar/hello.txt

2014年3月26日更新

在测试@gabrieloliveira建议时,我发现了以下内容:

header('Content-Type: plain/text');
header('Content-Disposition: attachment;filename=hello.txt');
header('X-Sendfile: '.$path.$file); // $path.$file outside quotes
header('Content-Length: '.filesize($path.$file)); // Filesize
echo '12345678901234567890';
exit;  

此脚本(我添加了echo’12345678901234567890′;)生成了包含以下16个字符串1234567890123456的文件的下载.16个字符与hello.txt的文件大小匹配.所以我们似乎可以得出以下结论

>内容长度&文件大小处理正确.
> X-SendFile无法找到该文件,或者:
> X-SendFile不处理该文件.

实际上,注释掉X-SendFile,就像这样:

// header('X-Sendfile: '.$path.$file);

产生相同的结果;无法识别执行X-Sendfile标头.

解决方法:

确保要提供的文件的路径与您在httpd.conf或httpd-vhosts.conf上的XSendFilePath指令中使用的路径相同

或者:您是否发送公共文件夹外的文件?如果是这样,那么将XSendFileAllowAbove添加到apache配置

标签:php,yii,x-sendfile
来源: https://codeday.me/bug/20190624/1279566.html