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

时间:2013-09-25 06:26:52

标签: php zend-framework2

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

提前感谢。

3 个答案:

答案 0 :(得分:7)

用户永远无法直接访问您的/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和native 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` 

如果我没有完全弄错,只需更换所有出现的双点就足够了......

答案 1 :(得分:2)

我会在公共目录中为数据文件夹中的PDF文件创建一个symbolic link

例如:

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

并创建类似

的链接
<a href="/pdf/file.pdf">File.pdf</a>

答案 2 :(得分:0)

借用Sam的代码,这是ZF2语法中的样子。

AttachedProperties