2012-02-20 56 views
0

我要求的解决方案如何使PHP下载文件,而无需重定向并没有在这个例子中读取文件源,如:PHP头文件路径

if(1 == 1) 
{ 
    header("Content-Type: application/xml"); 
    header("Content-Transfer-Encoding: binary"); 
    header("Cache-Control: private",false); 
    header("Content-Disposition: attachment; filename=example.xml;");  
    $file = file_get_contents("file.ext"); 
    echo file; 
} 

我需要不用其他file_get_contents下载解决方案使下载如mod_rewrite

感谢

+0

'PHP下载文件 - 这是不可能 – zerkms 2012-02-20 04:16:49

+1

@zerkms,没有它不:mod_xsendfile – Petah 2012-02-20 04:24:40

+0

@Petah:这是非常有趣的,谢谢 – zerkms 2012-02-20 06:34:45

回答

3

你可以使用Apache与X发送文件模块https://tn123.org/mod_xsendfile/

mod_xsendfile是一个小Apache2的模块,处理X-SENDFILE由原始输出处理程序注册 头。

如果遇到这种报头的存在,将丢弃所有 输出和发送,而不是使用Apache 内部包括像缓存-header和 的sendfile或MMAP所有优化如果配置为通过该标头中指定的文件。

它对于处理例如脚本输出是有用的。 PHP,Perl或任何 CGI。没有重定向和不读文件source`

+0

您好先生,感谢您的回答我的问题,如果我使用这个模块可以用户知道直接链接,我需要它隐藏 – user533178 2012-02-20 04:33:34

+0

@ user533178,没有你永远不要发送链接到客户端。你用PHP发送一个头文件,然后Apache选择它并自动重定向下载。 – Petah 2012-02-20 04:37:06

+0

感谢您的回答,这是非常好的解决方案 – user533178 2012-02-20 04:40:27

0

你可以让PHP发送文件直出的输出,而不是与readfile

编辑

我会建议,而不是一个变种阅读和直通的数据块,这应该会更好,因为它在启动输出之前不必读取整个文件。

if ($f = fopen($file, 'rb')) { 
    while(!feof($f) and (connection_status()==0)) { 
     print(fread($f, 1024*8)); 
     flush(); 
    } 
    fclose($f); 
} 
1
header("Pragma: public"); 
header("Content-Type: application/xml"); 
header("Cache-Control: private",false); 
header("Content-Type: application/force-download"); 
header("Content-Disposition: attachment; filename=file.ext;");  
readfile("file.ext"); 
+0

为什么是'标题(“附注:公共“);'需要? – Umbrella 2012-02-20 12:53:08

+0

你可以在这里阅读:) [http://stackoverflow.com/questions/1920781/what-does-the-http-header-pragma-public-mean](http://stackoverflow.com/questions/1920781/what -does-the-http-header-pragma-public-mean) – Fredy 2012-02-22 01:52:10

+0

这并没有描述它的要求。 – Umbrella 2012-02-22 03:29:53