Categories
Php

PHP-Zend 1: create an ImageController

During the development of a website I encountered the following problem: how to load some images located outside the document root into a ZF1 view? Obviously we could move these images into the document root but just to be sure we decided to leave them outside (these images are created with an external script), and in that place it’s impossible to get them with the standard approach (<img src=”relative/path”>¬†).

Now I found, thanks to a hint from a senior colleague, a way to overcome this problem: create a Zend Framework (we used the version 1.12.3 in this project) controller that has only to load the image and create a response with only the image within. By using a ZF controller you’ll be able to check if the user has the permission to open the image with a few queries and by using the current user session.

Now the only thing to do is to call this controller with a parameter: in the project I used the id of the image because the path is saved into a mysql table, but obviously you can use what you need.

Here comes the self-explanatory snippet of this controller:

<?php

class ImageController extends Zend_Controller_Action {
    public function thumbAction(){
        //controller headless, you don't need to create any views in this way
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender();

        //fullpath of the folder containing the thumbnails
        chdir(APPLICATION_PATH);
        $thumb_path = realpath("../path/from/zend/root");

        //with the id as parameter I find the row into the database
        $mapper = new Application_Model_YourImageTable();
        $row = $mapper->find($this->getRequest()->getParam('id'));

        //I check if the user is logged, otherwise I redirect to the homepage
        $auth = Zend_Auth::getInstance();
        if($auth->hasIdentity()){

            //now i can load the image because i know the path and it's name (stored into the db)
            $image = file_get_contents($thumb_path.'/'.$row->getThumb());

            //creating the response...
            $this->getResponse()->clearBody();
            $this->getResponse()->setHeader('Content-Type', 'image/png');
            $this->getResponse()->setBody($image);
       }
       else{
            //if the action is not permitted do something, in my case I redirect the user to the homepage
            $this->_helper->redirector('index', 'index');
       }
    }
}

 

Now when you want to load this image you only have to write a code like this:

<img src="<?php $this->url(array('controller' => 'image', 'action' => 'thumb', 'id' => $id)); ?>">

By croma25td

A post-degree computer science student actually in a internship with a web agency.