PHP不会显示页面和下载

agxfikkp  于 2023-04-19  发布在  PHP
关注(0)|答案(4)|浏览(124)

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

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页面是回显。但如果我删除下载,页面显示。

ds97pgxw

ds97pgxw1#

内容发送到浏览器后,你就不能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>
6bc51xsx

6bc51xsx2#

因为在推送自定义头文件之前无法输出任何内容,我建议使用JS重定向到下载,这通常会使您保持在同一页面上(只要您只是处理zip内容而不是其他内容)。
所以,试试这个:

$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指向它。像这样:
Download.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>
ars1skjm

ars1skjm3#

有一个简单的原则:
请记住,在发送任何实际输出之前,必须调用header(),无论是通过普通的HTML标记、文件中的空行还是从PHP发送。

解决方法是准备两个页面,一个显示html内容,一个下载。

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

1l5u6lss

1l5u6lss4#

如前所述,您不能在输出已经发送之后再发送头。
这可能对你有用:

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

<meta http-equiv="refresh"中的http-equiv意味着namevalue**等效于HTTP头,因此它与Refresh:头做同样的事情。
SourceForge下载任何文件,您将看到一个JavaScript实现(Your download will start in 5 seconds...)。

相关问题