php PHP生成文件下载然后重定向
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/822707/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP generate file for download then redirect
提问by Evan
I have a PHP app that creates a CSV file which is forced to download using headers. Here's the relevant part of the code:
我有一个 PHP 应用程序,它创建一个 CSV 文件,该文件强制使用标头下载。这是代码的相关部分:
header('Content-Type: application/csv');
header("Content-length: " . filesize($NewFile));
header('Content-Disposition: attachment; filename="' . $FileName . '"');
echo $content;
exit();
What I'd like to do is redirect users to a new page after the file is built and the download prompt is sent. Just adding header("Location: /newpage")to the end didn't work, expectedly, so I'm not sure how to rig this up.
我想做的是在构建文件并发送下载提示后将用户重定向到新页面。只是添加header("Location: /newpage")到最后并没有工作,所以我不知道如何装配它。
回答by daremon
I don't think this can be done - although I am not 100% sure.
我不认为这是可以做到的——尽管我不是 100% 确定。
The common thing (e.g. in popular download sites) is the reverse: first you go to the afterpage and then the download starts.
常见的事情(例如在流行的下载站点中)是相反的:首先您转到后页,然后开始下载。
So redirect your users to the finalpage that (among other things) says:
因此,将您的用户重定向到最终页面(除其他外)说:
Your download should start automatically. If not click [a href="create_csv.php"]here[/a].
您的下载应该会自动开始。如果没有点击[a href="create_csv.php"]here[/a]。
As about initiating the download (e.g. automatically calling create_csv.php) you have many options:
至于启动下载(例如自动调用 create_csv.php),您有很多选择:
- HTML:
[meta http-equiv="refresh" content="5;url=http://site/create_csv.php"] - Javascript:
location.href = 'http://site/create_csv.php'; - iframe:
[iframe src="create_csv.php"][/iframe]
- HTML:
[meta http-equiv="refresh" content="5;url=http://site/create_csv.php"] - Javascript:
location.href = 'http://site/create_csv.php'; - 框架:
[iframe src="create_csv.php"][/iframe]
回答by smnbbrv
very easy to do in the case it is really needed.
在真正需要的情况下很容易做到。
But you will need to have a bit work in JavaScript and cookies:
但是你需要在 JavaScript 和 cookie 方面做一些工作:
in PHP you should add setting up a cookie
在 PHP 中,您应该添加设置 cookie
header('Set-Cookie: fileLoading=true');
then on the page where you call the download you should track with JS (e.g. once per second) if there is coming cookie like that (there is used plugin jQuery cookiehere):
然后在您调用下载的页面上,如果有这样的 cookie(这里使用了插件jQuery cookie),您应该使用 JS 跟踪(例如每秒一次):
setInterval(function(){
if ($.cookie("fileLoading")) {
// clean the cookie for future downoads
$.removeCookie("fileLoading");
//redirect
location.href = "/newpage";
}
},1000);
Now if the file starts to be downoaded JS recognizes it and redirects to the page needed after cookie is deleted.
现在,如果文件开始被下载,JS 会识别它并在删除 cookie 后重定向到所需的页面。
Of course, you can tell you need browser to accept cookies, JavaScript and so on, but it works.
当然,你可以告诉你需要浏览器接受cookies、JavaScript等等,但它确实有效。
回答by ólafur Waage
The header you are sending are HTTP headers. The browser takes that as a page request and processes it as a page. And in your case, a page it needs to download.
您发送的标头是 HTTP 标头。浏览器将其作为页面请求并将其作为页面处理。在您的情况下,它需要下载一个页面。
So adding a redirect header to that confuses the whole process of downloading the file (since headers are collected, generated into one header and then sent to the browser, you can try this by setting multiple redirect headers IIRC)
所以添加一个重定向头来混淆下载文件的整个过程(因为头被收集,生成一个头然后发送到浏览器,你可以通过设置多个重定向头IIRC来尝试)
回答by Vaibhav Jain
This is quite old issue, but here is how I achieved it via JS.
这是一个很老的问题,但这是我如何通过 JS 实现的。
// Capture the "click" event of the link.
var link = document.getElementById("the-link");
link.addEventListener("click", function(evt) {
// Stop the link from doing what it would normally do.
evt.preventDefault();
// Open the file download in a new window. (It should just
// show a normal file dialog)
window.open(this.href, "_blank");
// Then redirect the page you are on to whatever page you
// want shown once the download has been triggered.
window.location = "/thank_you.html";
}, true);
回答by martar
Bear in mind, however, the automatic initiation of downloadable files for IE users will trigger the security warning tab. All three of the methods outlined by daremon would show this warning. You simply can't get around this. You will be better served if you provide real links.
但是请记住,为 IE 用户自动启动可下载文件将触发安全警告选项卡。达蒙概述的所有三种方法都会显示此警告。你根本无法解决这个问题。如果您提供真实链接,您将获得更好的服务。
回答by nikksan
<?php
function force_file_download($filepath, $filename = ''){
if($filename == ''){
$filename = basename($filepath);
}
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"" . $filename . "\"");
readfile($filepath); // do the double-download-dance (dirty but worky)
}
force_file_download('download.txt');
?>
<script type="text/javascript">
location = 'page2.php'
</script>
Here is a solution using javascript.
这是使用javascript的解决方案。
回答by Hisham Dalal
Here is the answer:
It's work!
You need three different parts of code:
HTML
这是答案:
这是工作!
您需要三个不同的代码部分:
HTML
<a id="download_btn" class="btn btn-primary" href="?file=filename&download=1">Download<&/a>
JQuery
查询
$('#download_btn').click(function(){
window.location.href = '<?=base_url()?>/?file=<?=$file;?>&download=1';
}).focusout (function(){
window.location.href = '<?=base_url()?>';
return false;
});
PHP
PHP
if(isset($_GET['download']) && isset($_GET['file'])){
$zip_path = 'path_to/'.$_GET['file'].'.zip';
if(file_exists($zip_path)){
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="'.basename($zip_path).'"');
header('Content-Length: ' . filesize($zip_path));
header('Location: '.$zip_path);
}
}
回答by Darren Crabb
I found one workaround for this that relies on javascript, so it's not exactly secure, but for non-secure critical sites it seems to work.
我找到了一种依赖于 javascript 的解决方法,因此它并不完全安全,但对于非安全的关键站点,它似乎有效。
Have a form with a button titled 'download' with the action set to point to the download script, then using javascript put something on the onsubmit handler that strips out the download button and replaces the messaging on the screen. The download should still happen and the screen will change. Obviously, if there's an issue with the download script then it still looks like the download was successful even if it doesn't fire, but it's the best I've got right now.
有一个带有标题为“下载”的按钮的表单,其操作设置为指向下载脚本,然后使用 javascript 在 onsubmit 处理程序上放置一些内容,该处理程序会去掉下载按钮并替换屏幕上的消息。下载应该仍然发生,屏幕会改变。显然,如果下载脚本存在问题,那么即使它没有触发,它看起来仍然是成功的,但这是我现在所拥有的最好的。
回答by Darren Crabb
You can try and redirect to the URL plus a parameter that represents the file contents. And in the redirect, you can output the file content for download.
您可以尝试重定向到 URL 以及表示文件内容的参数。在重定向中,您可以输出文件内容以供下载。
回答by Clinton
Launch the PHP file which contains the CSV download using:
使用以下命令启动包含 CSV 下载的 PHP 文件:
<a onclick="popoutWin(\'csvexport.php\')" >Download CSV File</a>
or
或者
<input name="newThread" type="button" value="Download CSV File"
onclick="popoutWin(\'csvexport.php\')" />
where the JavaScript function popoutWinis
在JavaScript函数popoutWin是
/*
* Popout window that self closes for use with downloads
*/
function popoutWin(link){
var popwin = window.open(link);
window.setTimeout(function(){
popwin.close();
}, 500);
}
This will open a window, to display the CSV download prompt and then immediately close the window, leaving only the prompt.
这将打开一个窗口,显示 CSV 下载提示,然后立即关闭窗口,只留下提示。

