Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PhpSpreadsheet return file instead of saving it

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.

like image 496
Brambor Avatar asked May 13 '18 18:05

Brambor


People also ask

How do I download PhpSpreadsheet library?

Use composer to install PhpSpreadsheet into your project. Or also download the documentation and samples if you plan to use them. A good way to get started is to run some of the samples. Don't forget to download them via --prefer-source composer flag.

How can I open XLSX file in PHP?

Read an Excel File (XLSX)​ Open the XSLX file with $reader->open($path) Browse each Sheet of the spreadsheet with $reader->getSheetIterator() Browse each Row of the Sheet with $sheet->getRowIterator() Browse each Cell of the Row with $row->getCells()


2 Answers

Use php://output

header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename="file.xls"');
$writer->save("php://output");
like image 177
Artyom Sokolov Avatar answered Sep 24 '22 05:09

Artyom Sokolov


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;
like image 44
Syscall Avatar answered Sep 25 '22 05:09

Syscall