正在从 PHP 项目的 tmp 文件夹下载 CSV

Downloading a CSV from tmp folder of PHP project

我目前正在开发一个使用 Zend Framework 的 PHP 项目。我在控制器中制作了一个没有任何问题的 CSV,但随后希望用户能够通过单击视图中的按钮来下载文件。

在我的 .phtml 我有:

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

$this->download 正在控制器中设置:

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

_createCSV 函数创建 CSV 并将其存储在站点使用的临时目录中。然后 returns 文件路径。

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; 
}

单击按钮时,浏览器尝试下载文件,但由于找不到文件而出错。这是有道理的,因为浏览器不应该访问临时文件夹,但我不完全确定如何解决这个问题。

如果您由于 UNIX 文件权限而无法看到该文件夹​​,那么您唯一的选择是:

  1. 更改 tmp 文件夹的文件权限,以便您的 Web 服务器可以 read/write 使用 chmod/chown(我假设它是一个 linux 系统?)
  2. 使用具有足够权限的其他文件夹
  3. 不要将文件存储在磁盘上 - 而是将其存储在数据库中(不是最优的)。

一旦您确定您的文件权限是有序的并且该文件可以被 apache 读取,it appears that you should be able to use php's readfile 函数将文件实际传输回浏览器:

<?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;
}
?>