如何在 zend 框架中访问数据文件夹中的文件


How to access files in data folder in zend framework?

目前我正在研究ZF2。现在我必须提供下载选项来下载pdf文件.我已经将所有pdf文件存储在data目录中。如何指定从 .phtml 文件指向该 pdf 文件的链接?

提前谢谢。

用户将永远无法直接访问您的/data目录。这不会那么好。但是您可以轻松地为自己编写一个download-script.php或类似内容,以将此目录的内容分发给您的用户。

如果您查看public/index.php的前六行,您将看到以下内容:

<?php
/**
 * This makes our life easier when dealing with paths. Everything is relative
 * to the application root now.
 */
chdir(dirname(__DIR__));

考虑到这一点,您知道从 PHP 的角度来看,访问 data 目录中的任何内容就像data/file.pdf一样简单

你总是想给自己写某种下载记录器。给自己写一个控制器。在该控制器内部执行一个操作,可能称为类似download或类似的东西。该操作应具有一个参数filename

此操作所做的只是检查文件名是否存在file_exists('data/'.$filename)如果存在,您只需将此文件传递给用户即可。一个示例 mix或 zf2 和本机 php 可以是:

public function downloadAction() 
{
    $filename = str_replace('..', '', $this->params('filename'));
    $file     = 'data/' . $filename;
    if (false === file_exists($file)) {
        return $this->redirect('routename-file-does-not-exist');
    }
    $filetype = finfo_file($file);
    header("Content-Type: {$filetype}");
    header("Content-Disposition: attachment; filename='"{$filename}'"");
    readfile($file);
    // Do some DB or File-Increment on filename download counter
    exit();
}

这不是干净的 ZF2,但我现在很懒。使用适当的Response对象并在那里进行文件处理可能更理想!

重要更新 这件事实际上也很不安全。您需要禁止父文件夹。你不会想让这个家伙做一些data/download目录之外的事情,比如

`http://domain.com/download/../config/autoload/db.local.php` 

如果我没有完全弄错的话,简单地替换所有出现的双点就足够了......

我会在公共目录中为数据文件夹中的PDF文件创建一个符号链接。

例如:

ln -s /your/project/data/pdfdir /your/project/public/pdf

并创建类似

<a href="/pdf/file.pdf">File.pdf</a>

用Sam的代码,下面是它在ZF2语法中的样子。

public function downloadAction()
{
    $filename = str_replace('..', '', $this->params('filename'));
    $file     = 'data/' . $filename;
    if (false === file_exists($file)) {
        return $this->redirect('routename-file-does-not-exist');
    }
    $filetype = finfo_file($file);
    $response = new 'Zend'Http'Response'Stream();
    $response->getHeaders()->addHeaders(array(
        'Content-Type' => $filetype,
        'Content-Disposition' => "attachement; filename='"$filename'""
    ));
    $response->setStream(fopen($wpFilePath, 'r'));
    return $response;
}