Raptor
Raptor

Reputation: 54212

PHP Header : Content-disposition: attachment , then Location: some url

My goal is to redirect browser to a new page after browser issues the attachment download.

header("Content-type: text/csv");
header("Cache-Control: no-store, no-cache");
header("Content-disposition: attachment;filename=file.csv");
// csv output logic here

// forward to next page
header("Location: $url");

Is it possible ?

UPDATE : the result of above

The last line of CSV shows PHP error :

Cannot modify header information - headers already sent by...

It is because CSV logic part has modified the contents before the line header("Location: $url");

UPDATE : I tried an alternative method: to echo a small HTML consist of a key line <meta http-equiv="refresh" content="0; url=$url" /> ( of course <html> <head> <body> and even DOCTYPE are also echoed ). But still, the HTML codes are shown in the CSV content.

Upvotes: 4

Views: 4671

Answers (2)

AKS
AKS

Reputation: 4658

With the current code, no you can't. You force the browser to download the further content to file.csv so newer headers are ignored.

However, have a look at meta refresh stuff. You will be able to add a delay between the page load (so user actually sees a web page) and send the file to download in the refresh.

I wish I could add an example but I'm currently in a train surrounded by some babies crying and I'm bored.

To prevent the meta tags (and other HTML) appearing in the CSV file content, we can use some $_GET value.

<?php
if (isset($_GET['dl']) && $_GET['dl'] == '1') {
header("Content-type: text/csv");
header("Cache-Control: no-store, no-cache");
header("Content-disposition: attachment;filename=file.csv");
// csv output logic here
}
else{
?>
web page here, with html, head, title, body, and whatnot tags. 
In the head tag, add this:
<meta http-equiv="refresh" content="5;url=http://my.web.site.com/download.php?dl=1"> 
<?php
}
?>

Upvotes: 3

Adam D. Ruppe
Adam D. Ruppe

Reputation: 25595

You could do it client side: open the file download in a new window and then redirect the current window with javascript.

Upvotes: 1

Related Questions