简体   繁体   中英

write csv in ram and output file to user [php]

First of all, I found a similar question , but that doesn't do the trick when if I understand it correctly.

I'm creating a csv-file with PHP with the following function(s).

 // open the file. If not existent yet, create it first
 if (!file_exists($this->filename))
 {
     touch($this->filename);
 }

 $handle = fopen($this->filename, "w+");
 if ($this->includeHeaders)
 {
     $headers = array('Company', 'Contactperson', 'Username', 'Commission', 'WinCAP Version', 'WinCAP Link', 'Contract due', 'POS Version', 'POS Link', 'Quick Select Version', 'Quick Select Link', 'Password');
     fputcsv($handle, $headers);
 }

 // mysql-stuff here

 while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
 {
     fputcsv($handle, $row, ";", '"');
 }

 // done
 fclose($handle);

As you can tell, it is TYPO3 -related, but that shouldn't bother here. However, my file is generated correctly, containing all the data I need. However, the file is created on the filesystem. That means, anyone with the link to that file, can download it.

This is what I want to prevent. I was thinking about adding a hash, but that doesn't seem to protect it well enough. So I cam up with the idea: why not just open the save-file dialog , after creating that file. This means, the file shouldn't be stored on the FS, right?

I read a bit about the output-buffer , but what would the file for the $handle be? PHP:\\\\out?

Just to clarify: User clicks "export" -> after proccessing the data and finishing the file, show SAVE-dialog in Browser. Don't save the file on the FS.

Just send the file for download and then delete it. Add this right after your code:

// Send correct http headers
header('Content-Description: File Transfer');
header("Content-Type: application/csv") ;
header("Content-Disposition: attachment; filename=ChooseFilename.csv");
header("Expires: 0");

// Send file to browser
readfile($this->filename);

// delete file
unlink($this->filename);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM