Reputation: 664
I have generated xmlx file and I am able to save it and provide it for the user via:
$writer->save('hello world.xlsx');
header('Location: hello world.xlsx');
However, then the file remains on the hard drive. I need to get rid of it as it is a security threat.
I tried unlinking the file
unlink('hello world.xlsx');
but that deletes the file too early so the user doesn't have access to it.
If it can work with unlink then I need to be sure the file will be deleted (so proper using of die();
and such)
EDIT: It is not only for security reasons anymore. The provider doesn't allow saving files so it is the only way to go.
Upvotes: 10
Views: 24258
Reputation: 163
You can use an in memory file pointer and read back from it.
$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
$fp = fopen("php://memory", "rw");
$writer->save($fp);
rewind($fp);
$contents = "";
while (!feof($fp)) {
$contents .= fread($fp, 8000);
}
Upvotes: 3
Reputation: 1676
ob_end_clean();
$writer->save('php://output');
Upvotes: 1
Reputation: 2405
Use php://output
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename="file.xls"');
$writer->save("php://output");
Upvotes: 20
Reputation: 19780
You could send the file directly after its creation, instead of the redirect to the file.
$filename = 'hello world.xlsx';
$writer->save($filename);
// Set the content-type:
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Length: ' . filesize($filename));
readfile($filename); // send file
unlink($filename); // delete file
exit;
Upvotes: 4