【问题标题】:Downloading a CSV from tmp folder of PHP project从 PHP 项目的 tmp 文件夹下载 CSV
【发布时间】:2016-06-14 15:04:29
【问题描述】:

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

在我的.phtml 我有:

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

$this-&gt;download 正在控制器中设置:

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

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

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

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

【问题讨论】:

标签: php csv zend-framework download


【解决方案1】:

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

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

一旦你确定你的文件权限是有序的并且文件可以被 apache 读取,it appears that you should be able 使用 php 的 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;
}
?>

【讨论】:

  • 我认为这不是文件权限的问题,而是tmp 目录没有托管在网站上的任何地方。
  • 那么您正在寻找的是一种打开临时文件并提供它的方法,而无需它实际上是 Web 服务器配置文件中网站范围的一部分?你用的是什么网络服务器?
  • 是的,差不多。我可以访问服务器端的文件,但我希望它可以在客户端下载,所以我需要弄清楚如何将它传递给客户端。我正在使用 Apache
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-07-07
  • 2020-09-17
  • 2016-10-15
  • 1970-01-01
  • 1970-01-01
  • 2019-02-24
  • 1970-01-01
相关资源
最近更新 更多