Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File download issue in PHP with Content-Disposition: attachment

I have a link on my web page to download a .CSV file that I have generated on the server. The code for the download is as follows:

//open/save dialog box
header('Content-Disposition: attachment; filename="inventoryData.csv"');
//content type
header('Content-type: application/excel');
//read from server and write to buffer
readfile('spreadsheet/inventory.csv');

When I open the file on the server, it looks just fine. However, when I download the file via the dialog box, it is pre-pending the HTML code for the web page to the .csv file.

Any ideas why that would happen?

like image 461
scott80109 Avatar asked Dec 31 '25 11:12

scott80109


1 Answers

If this code is in a controller action which I assume it is since you are using ZF, then you need to disable your layout and the view renderer as it will try to render a view.

Try:

public function downloadAction()
{
    $this->_helper->layout()->disableLayout();
    $this->_helper->viewRenderer->setNoRender(true);

    //...

    //open/save dialog box
    header('Content-Disposition: attachment; filename="inventoryData.csv"');
    //content type
    header('Content-type: application/excel');
    //read from server and write to buffer
    readfile('spreadsheet/inventory.csv');
}

$this->_helper->layout()->disableLayout(); prevents your layout script from being rendered (assuming you use layouts), and $this->_helper->viewRenderer->setNoRender(true); tells the view renderer not to render the view script for the controller action which may contain some HTML or whitespace.

like image 158
drew010 Avatar answered Jan 02 '26 23:01

drew010



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!