Sara Fuerst
Sara Fuerst

Reputation: 6068

Downloading a CSV from tmp folder of PHP project

I currently am working on a PHP project that uses the Zend Framework. I am making a CSV without any issues in the controller, but then want the user to be able to download the file by clicking a button in the view.

In my .phtml I have:

<a class="btn" href="<?php echo $this->download;?>" download>Export to CSV</a>

$this->download is being set in the controller:

$view["download"] = $this->_createCSV($bqc_jobs, $startDate, $endDate, $processor_id, $defaultTime);

The _createCSV function creates the CSV and stores it in the temporary directory that the site uses. It then returns the filepath.

private function _createCSV($jobs, $start, $end, $user=null, $minutes){
    $format = "Ymd_His";
    if(!$start && !$user){
        $start = date($format, strtoTime("-" . $minutes . " minutes"));
    }

    if(!$end){
        $end = \DateTime::createFromFormat($format, date($format))->format($format);
    }
    $directory = Config::$tempDir; 
    $fileName = $directory . "/" . ($user ? $user . "_" : "") . ($start ? $start . "_" : "") . $end . "_report.csv";  

    $file = fopen($fileName, 'w'); 
    foreach ($jobs as $job){
        fputcsv($file, $job); 
    }

    fclose($file); 

    return $fileName; 
}

When the button is clicked, the browser tries to download the file, but errors because it cannot find the file. This makes sense, since the browser should not have access to the temporary folder, but I'm not entirely sure how to get around this.

Upvotes: 1

Views: 2420

Answers (1)

James Shewey
James Shewey

Reputation: 270

If you are unable to see the folder due to the UNIX file permissions, then your only options will be to:

  1. Change the file permissions on the tmp folder so that your web server can read/write there using chmod/chown (I assume it is a linux system?)
  2. Use a different folder with sufficient permissions
  3. Don't store the file on disk - store it in a database instead (not optimal).

Once you are sure your file permissions are in order and that the file can be read by apache, it appears that you should be able to use php's readfile function to actually transmit the file back to the browser:

<?php
$file = '/tmp/monkey.gif';

if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="'.basename($file).'"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    readfile($file);
    exit;
}
?>

Upvotes: 1

Related Questions