PHP readfile with PHPPowerpoint issue

1.3k views Asked by At

I am using PHPPowerpoint to create a pptx file with some charts, and have no problem storing it in the same folder as the PHP script. PHPPowerpoint does that on itself.

I want to download the pptx file after it has been created, and so far I have tried every option I could locate on the web. This is how i try to do it atm.:

$file = str_replace('generate_report.php', 'export_download.pptx', __FILE__);
header('Content-Description: File Transfer');
header('Content-disposition: attachment; filename="' . $file . '"');
header('Content-Transfer-Encoding: binary');
header('Content-Type: application/vnd.openxmlformats-officedocument.presentationml.presentation');
header('Expires: 0');
header('Cache-Control: ');
header('Pragma: ');
flush();
ob_clean();
readfile($file);

Nothing is downloaded when I execute the script. My pptx is created on the server and I can open it, no problem. But it wont download the file. I got the content type from this thread: What is a correct mime type for docx, pptx etc?. I also tried with many other types. When I console log my response i get a weird string (very long), beginning like this: PKCTDD����[Content_Types].xml͗�n�0E�|E�-J��*�X�����+���m���wBhE

Also tried this:

$handle = fopen($file, 'rb');
$buffer = '';
while (!feof($handle)) {
$buffer = fread($handle, 4096);
echo $buffer;
ob_flush();
flush();
}
fclose($handle);

Anybody who can help?

1

There are 1 answers

7
Mark Baker On

The following headers should work; and it's also better streaming directly to php://output rather than save to disk file and then spooling that disk file to the browser

// Redirect output to a client’s web browser
header('Content-Type: application/vnd.openxmlformats-officedocument.presentationml.presentation');
header('Content-Disposition: attachment;filename="' . $file . '"');
header('Cache-Control: max-age=0');
// If you're serving to IE 9, then the following may be needed
header('Cache-Control: max-age=1');

// If you're serving to IE over SSL, then the following may be needed
header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
header ('Pragma: public'); // HTTP/1.0

$objWriter = PHPPowerPoint_IOFactory::createWriter($objPHPPowerPoint, 'PowerPoint2007');
$objWriter->save('php://output');