0

I am creating a CSV file in PHP, no biggie there, and then force downloading it for the user, again no biggie there. The problem I am coming across is the redirect portion. I know that you cannot create a file and push to the user and then use php redirect afterwards, as it kills the CSV creation due to the HTTP protocols. So instead, I am doing a javascript redirect as follows:

echo '<script>';
echo '    window.location = "'.base_url().'link/'.$item_id.'"';
echo '</script>';
die;

This works fine (it reloads the page), but the portion above that is echoed gets added on to the CSV file when it is downloaded. Here is the php code that creates the CSV and force downloads it:

fwrite($csv, $csv_data);
fclose($csv);

header('Content-type: application/vnd.ms-excel');
header('Content-Length: ' . strlen($csv_data));
header("Content-disposition: attachment; filename=$file_name");
readfile($file_path);

What am I missing in terms of not having the <script> text getting appended to the CSV?

Thanks in advance.

klye_g
  • 1,242
  • 6
  • 31
  • 54
  • when using content-disposition everything on the page that gets echoed will be downloaded, you can not partially download a page and have the rest rendered into the browser. – Patrick Evans Mar 11 '14 at 15:22
  • possible duplicate of [Header redirect after download](http://stackoverflow.com/questions/5962771/header-redirect-after-download) – Patrick Evans Mar 11 '14 at 15:22
  • @PatrickEvans, the csv creation occurs just before the echo of the script. I think I might try a different approach where a session or cookie value gets set that tells the page (after reloading) to create a csv and download it. – klye_g Mar 11 '14 at 15:23
  • try `die;` after creating cvs. When I see your url, I guess it creates the CVS and continues the script told him to make echo... – doydoy44 Mar 11 '14 at 16:52

0 Answers0