如何限制对使用PHP创建的CSV文件的下载访问?

Objective:

I need to create a CSV file via PHP but limit download access to the member responsible for the creation of the file.

Context:

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.

What I've tried:

<?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 question:

  1. How do I limit download access to the member that creates the CSV file?
  2. Can an overlap occur between members when creating the CSV file since it's essentially a shared file?

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?

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.