3

I feel like I am missing obvious here, but I will post anyway.

I have a 'csv.php' which creates a csv file, simple example:

// csv.php
$fh = fopen('report.csv', 'w') or die("can't open file");
while ($row = mysql_fetch_row($result)) { 
    fputcsv($fh, $row);
}
fclose($fh);

On a seperate page, there is a simple anchor element that links to the file above. So on home.html there is:

<a href='report.csv'>Report</a>

One user will run csv.php and another will goto home.html and click the link at a later point in time. This works fine, the CSV is created, the data is there, and the anchor links through.

I know that if I were echoing out the CSV, I would add the various headers such as:

header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");

But how do I add these headers to the file report.csv? I assume this is required because firefox refuses to see the csv as a downloadable file (when the anchor is clicked, it just outputs the csv to the browser).

2
  • 1
    If you're running Apache, you could force the download using your .htaccess file: css-tricks.com/snippets/htaccess/… Commented Sep 28, 2011 at 0:55
  • 1
    You can also use mod_cern_meta or mod_headers to piggyback those extra headers via .htaccess Commented Sep 28, 2011 at 1:22

2 Answers 2

5

You won't be able to add the headers to the report.csv itself. You can alternately have a proxying script, something like download.php?report=report.csv

Then, you would do something like the following:

$csv = file_get_contents("./csv_directory/" . preg_replace("#/#", "", $_GET['report']);
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");
echo $csv;

Big Note
As @Pat mentioned (while I was looking for the appropriate syntax), you can use .htaccess or modify httpd.conf itself if you are using apache and have access. This, in my opinion, is a better way to solve your problem.

Sign up to request clarification or add additional context in comments.

1 Comment

Obviously I have no error handling in there, and very little security (just a preg_replace), but you should get the idea from that.
2

Headers aren't part of a file, they're part of an HTTP response.

If your web server is not setting the headers you want for csv files, you can probably convince it to do so.

Or, if you can't (or don't want to), see sberry2A's answer, to serve the file via php, and control the web server that way.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.