【问题标题】:CodeIgniter3 - where to store PDF files?CodeIgniter3 - 在哪里存储 PDF 文件?
【发布时间】:2018-01-16 15:49:30
【问题描述】:

我使用 CodeIgniter3 来构建项目。 但是我不确定存储生成的 PDF 文件的最佳位置在哪里。 由于 MySQL 的大小,我不想将它们保存在 MySQL 中。

我不希望人们访问直接链接,例如:http://mydomain/pdf/file.pdf 但我想为 codeigniter 登录用户提供这种访问权限。

最好的方法是什么?

【问题讨论】:

  • 在应用程序文件夹之外,您可以在主目录中创建另一个名为 downloads 的文件夹

标签: php codeigniter file pdf codeigniter-3


【解决方案1】:
  1. 创建site/pdf_files/.htaccess 文件并添加这一行:

    Deny from all
    
  2. 如下进行路由器配置

    /*
     anything in second segment of pdf controller will be routed to
     index method 
    
     serve file like : 
     http://example.com/pdf/myfile.pdf
    */
    $route['pdf/(:any)'] = "pdf/index/$1";
    
    /*
     Note: if you got some more methods in same controller prefer below one
     because, with above one, anything in second segment will be routed to 
     index method  
    
     $route['pdf/display/(:any)'] = "pdf/index/$1";
    
     and serve files like
     http://example.com/pdf/display/myfile.pdf
    */
    
  3. 然后在向用户提供 pdf 时更喜欢下面的 codeigniter 文件帮助器

    class Pdf extends CI_Controller
    {
    
    function download_file($path, $name)
    {
      // make sure it's a file before doing anything!
      if(is_file($path))
      {
    
        // get the file mime type using the file extension
        $this->load->helper('file');
    
        header('Content-Type: '.get_mime_by_extension($path));  
        header('Content-Disposition: attachment; filename="'.basename($name).'"');  // Add the file name
        header('Content-Transfer-Encoding: binary');
        header('Content-Length: '.filesize($path)); // provide file size
        header('Connection: close');
        readfile($path); 
        die();
      }
    }
    
     public function index($file)
     {
        // here you check whether user logged in or not
    
         $this->download_file('pdf_files/'.$file, $file);
     }
    }
    

【讨论】:

  • @Tikky 让它更安全,将function download_file($path, $name) 更改为private function download_file($path, $name)
  • 你好,我试过了,但是当使用 attach() 时,它不起作用,当我删除 de .htacess 文件时它起作用了。 ://
【解决方案2】:

将 PDF 存储在文档根目录之外的不公开位置。

您可以使用应用程序逻辑来允许登录用户查看/访问:

class pdf extends ci_controller{

     public function view()
     {
        //check if user is logged in and has permission to view
        //set proper header information
        //readfile('non_public_path\to\pdf);
     }

}

只要您的 pdf 在您的公共目录之外 - 发送请求到 domain.com/pdf/view 将仅在用户登录并有权查看时呈现 pdf。

【讨论】:

    猜你喜欢
    • 2012-01-20
    • 2011-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-24
    • 2016-03-14
    • 2013-10-02
    相关资源
    最近更新 更多