1

Can anyone help me to write code on PHP to download Excel File from the server.

I have created below codes using header and readfile but the downloaded file was corrupted.

//content type
header('Content-type: application/vnd.ms-excel');
//open/save dialog box
header('Content-Disposition: attachment; filename='.$fileName);
//read from server and write to buffer
readfile($reportPath);

Can anyone help me on the best way to download existing Excel file from the server.

Please see below image of data after downloadedenter image description here

Mark
  • 314
  • 1
  • 5
  • 17
  • So how are you actually creating this file? – Mark Baker Jun 11 '13 at 13:05
  • I'm creating this file using PHPExcel.. But the error was in download part. Since I've also tested to open an excel then have some data then save and upload it to the server. but still errors on output file when downloading.. – Mark Jun 11 '13 at 13:08

3 Answers3

2
ob_clean();

put that code before all header declaration

Mark
  • 314
  • 1
  • 5
  • 17
0

I suggest to use the X-SENDFILE header. https://tn123.org/mod_xsendfile/

Fracsi
  • 2,274
  • 15
  • 24
  • is there anything to add on server configuration to used X-SendFILE?? – Mark Jun 11 '13 at 13:11
  • You have to enable the module. Also you have to configure the virtualhost to what files to serve. In the php you have to set only a header. – Fracsi Jun 13 '13 at 05:44
0

I use something like the following:

header("Content-Description: File Transfer");
header("Content-Type: application/octet-stream");
header('Content-Disposition: attachment; filename="'.basename($path).'"');
header("Content-Transfer-Encoding: binary");
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header("Content-Type: application/force-download");
header("Content-Type: application/download");
header("Content-Length: ".filesize($path));
readfile($path);
exit;

Make sure you're not outputting anything before or after the readfile.

periklis
  • 10,102
  • 6
  • 60
  • 68
  • sadly but still having the same error when opening downloaded excel file – Mark Jun 11 '13 at 13:14
  • Try with a txt file and see how it's downloaded. Is its original content intact? – periklis Jun 11 '13 at 13:20
  • I've already try with txt file, content is as is.. But why excel can't get the actual content? – Mark Jun 11 '13 at 13:33
  • A common case is when there's an invisible, unprintable character preset in the output that messes with your file (especially if you're not using english). what if you turn on error reporting, do you get anything? Put this right above your first header(): `error_reporting(E_ALL);ini_set('display_errors', true);` – periklis Jun 11 '13 at 13:37