A web developer's blog. PHP, MySQL, CakePHP, Zend Framework, Wordpress, Code Igniter, Django, Python, CSS, Javascript, jQuery, Knockout.js, and other web development topics.

File Downloads With Zend Framework

I have been handling file uploads in most of my web applications. Sometimes, I store them in databases and sometimes I feel like storing them in directories. This post will not deal with uploading files, but rather downloading them. Basically, I used PHP’s readfile() function to read the file and then output it – with the headers set. So here goes…


< ?php class ResearchController extends Zend_Controller_Action
{
...rest of the code here...
 
    function downloadFileAction()
    {
        $id = $this->getRequest()->getParam('id');
        $filename = $this->getRequest()->getParam('filename');
        $path = Zend_Registry::get('uploadDir').$id.'/'.$filename;
        header('Content-Type: application/octet-stream');
        echo readfile ($path);
        exit;  //this is important! you will get a corrupted file if you do not put exit;
    }
}
...rest of the code here...

uploadDir is not accessible through the URL. This is an instance of Zend_Registry which is coded inside the bootstrp file (the index.php in ZF). Let’s just say that it is located in /home/ekini/uploads. While the website is located at /home/ekini/public_html/. The reason for storing the files outside the publicly accessible directly is so that no body can access the file using the URL. For example, if you put your upload directory inside public_html, anyone can access it using this URL: http://www.mysite.com/uploads/confidential_file.pdf. You can avoid this by simply putting out anywhere outside the public_html directory.

In my view file, I would have something like this:

http://www.mysite.com/research/downloadFile/id/16/filename/HelloWorld.pdf

Where research is the controller, downloadFile is the action, id is the directory inside uploadDir which stores the file that is named: HelloWorld.pdf.

The post is pretty rough on the edges, but I hope you got the idea.

This entry was posted in General and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>