Reputation: 2268
I need to create a CSV file via PHP but limit download access to the member responsible for the creation of the file.
Website members have the option of outputting their profile data to a CSV file. The created CSV file represents a potential privacy issue. I'm concerned that if two members simultaneously create the CSV file, an overlap could result in one member's data being revealed to another.
<?php
$list = array (
array('1', '2', '3', '4'),
array('a', 'b', 'c', 'd')
);
$fp = fopen('file.csv', 'w');
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
?>
<!--File is in root-->
<a href="/file.csv">Download file.csv</a>
My idea so far is to give each CSV file a unique name rather rewriting the same file. That'll solve the the overlap issue though the files are still accessible when targeted in a browser. I can assign the CSV files to restricted folder but it's probably more ideal to destroy the file once its downloaded.
Is there a better approach to all of this?
Upvotes: 1
Views: 759
Reputation: 67695
The easiest way is to just output the data to stdout
and send the proper headers when your script is called.
Per example, you have this HTML link:
<a href="download_csv.php">Download as CSV</a>
In download_csv.php
, you just do:
$list = array (
array('1', '2', '3', '4'),
array('a', 'b', 'c', 'd')
);
// Send the proper headers
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename=results.csv');
// Open stdout instead of an actual file
$fp = fopen('php://output', 'w');
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
This'll fix both of your problems.
Upvotes: 5