Search code examples
phpcodeigniterexportforce-download

Stop infinite loop in force download


While fixing a download issue related to CSV, I have added some headers that are commonly available in PHP. After, adding those I have performed a CSV export test. From that point onward in my browser, a new tab is opening & closing infinitely. I was not able to stop it by reverting the update that I have made. Cleared server & browser - cache & history. Still, the tabs are reopening while trying to export with older code. I'm now stopping the browser(Chrome) by executing sudo pkill -9 chrome on the terminal.

I think the new tab opening & closing is related to the force download code that I have added.

header('Content-Description: File Transfer');
header('Content-Transfer-Encoding: binary');
header('Content-Disposition: attachment; filename='.$filename);
header('Content-Type: application/csv;');
header('Content-Type: application/force-download');
header('Content-Type: application/octet-stream', false);
header('Content-Type: application/download', false);

// file creation 
$file = fopen('php://output', 'w');
$header = array("Group Name","Contact Name","Email","Phone Number","Company Name"); 
fputcsv($file, $header);
foreach ($new_array as $key => $line){ 
    fputcsv($file,$line); 
}
fclose($file); 
exit;

$new_array is an array of data taken from DB.

I think the issue was because of the reason that I forgotten to add cache header like:

header('Cache-Control: public, must-revalidate, max-age=0');
header('Pragma: public');
header('Expires: Sat, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');

Is there any way to stop this issue?

A video link to see the issue


Solution

  • @MagnusEriksson's comments were correct.

    It was not an issue with PHP/JS or even with the browser.

    I was asked to test the CSV file by open in the browser to check the issue & I have tried the "open with" option provided by the system. And that resulted in the issue, the downloaded file after clicking the export option was trying to open in the browser window which led to downloaded the same file again & it went on like an infinite loop.

    This is not a code-related issue but it has taken my whole day. I have searched a lot related to PHP headers.

    I'm also adding a few valuable comments from @MagnusEriksson's below:

    • No PHP code can make tabs in the browser open and close.

    • You seem to have two different problems. 1. There's no download (which most likely is PHP). 2. The tab keeps opening and closing (this can not be caused by PHP since PHP can't open or close tabs in the client). That looks like some JS/browser issue.