2012-08-10 47 views
1

我试图在下载文件之前用PHP显示HTML页面。我知道我不能重定向到一个不同的页面并同时下载一个文件,但为什么这不起作用?PHP不会显示页面并下载

echo "<html>...Example web page...</html>"; 

$download = '../example.zip'; //this is a protected file 

header('Content-Type: application/zip'); 
header('Content-Disposition: attachment; filename=example.zip'); 
readfile($download); 

文件下载,但它从不显示回显的HTML页面。但是如果我删除下载,页面显示。

+2

打印内容后无法发送自定义标题。 – 2012-08-10 03:04:28

+0

@navnav谢谢。你推荐我做什么? – 2012-08-10 03:05:56

+0

啊,所以你不希望他们看到文件路径? – 2012-08-10 03:19:16

回答

0

因为你可以推定制标题之前不能输出任何东西,我会建议使用JS重定向到下载,这通常让你在同一页上(只要你只是处理压缩的内容,没有别的)。

所以,试试这个:

$download = 'example.zip'; 

echo '<head> <script type="text/javascript"> function doRedirect(){window.location = "'.$download.'"}</script> 

</head><html><script type="text/javascript"> doRedirect() </script> <...Example web page...</html>'; 

或者,如果你需要它的计时器:

echo '<head> <script type="text/javascript"> function doRedirect(){window.location = "'.$download.'"}</script> 

</head><html><script type="text/javascript"> 
setTimeout(doRedirect(),1000);//wait one second</script> <...Example web page...</html>'; 

编辑:

如果你想隐藏的文件路径,我会建议制作一个下载脚本,JS将重定向到。

所以基本上,要做你正在做的事情,然后用JS指出它。像这样:

下载。PHP:

//use an ID or something that links to the file and get it using the GET method (url params) 

    $downloadID = $_GET['id']; 

    //work out the download path from the ID here and put it in $download 
if ($downloadID === 662) 
{ 
    $download = 'example.zip';//... 
} 
    header('Content-Type: application/zip'); 
    header('Content-Disposition: attachment; filename=$download'); 
    readfile($download); 

,然后在主HTML文件,使用JS指向它,用正确的ID:

<head> <script type="text/javascript"> function doRedirect(){window.location = "Download.php?id=662"}</script> 

</head><html><script type="text/javascript"> doRedirect() </script> <...Example web page...</html> 
0

有一个简单的原则:

记住头之前任何实际产量 发送,无论是普通的HTML标记,空行的文件,或者从PHP()必须被调用。

解决方案是准备两个页面,一个用于显示HTML内容,一个用于下载。

在页面1中,使用javascript设置一个定时器,在几次之后重定向到下载链接。例如,“5秒后,下载将开始。”

1

将内容发送到浏览器后,您不能set header information。如果你真的得到下载 - 可能有一些输出缓存在某个地方。

对于你要完成什么,你可能想显示HTML内容,并使用<meta>标签或JavaScript重定向到下载脚本。我相信大多数浏览器将开始下载,同时保持用户可以看到上次加载的页面(实际上应该是你想要做的)。

<meta http-equiv="refresh" content="1;URL='http://example.com/download.php'"> 

或者:

<script type="text/javascript"> 
    window.location = "http://example.com/download.php" 
</script> 
0

正如已经说过,你不能发送标题后输出已经发送。

所以,这可能会为你工作:

header('Refresh: 5;URL="http://example.com/download.php"'); 
header('Content-Type: application/zip'); 
header('Content-Disposition: attachment; filename=example.zip'); 
readfile($download); 

http-equiv<meta http-equiv="refresh"意味着namevalue当量 alent到HTTP标头,所以它做同样的事情的Refresh:头。

SourceForge下载任何文件,您将看到一个JavaScript实现(Your download will start in 5 seconds...)。