How To Serve Images With a Kohana Controller

If you want to serve images using a Kohana controller you can follow these steps.

  1. Define a Route that will catch all image requests
  2. Create a Controller_Images class for handling image requests
  3. Create an action for passing thru the image back to the user
The Route
  /home/kerkness/kohana/application/bootstrap.php
  Route::set('images', 'image/<file>', array('file' => '.+.(?:jpe?g|png|gif)'))
      ->defaults(array(
          'controller' => 'images',
          'action' => 'index',
      ));
The Controller
  /home/kerkness/kohana/application/classes/controller/images.php
  class Controller_Images extends Controller {
  
      protected $directory = 'static/images/';
  
      public function action_index()
      {
          // Create the filename
          $file = $this->directory.$this->request->param('file');
  
          if ( ! is_file($file))
          {
              throw new Kohana_Exception('Image does not exist')
          }
  
          //
          // Check your permissions here
          //
  
          // Set the mime type
          $this->request->headers['Content-Type'] = File::mime($file);
          $this->request->headers['Content-length'] = filesize($file);
  
          // Send the set headers to the browser
          $this->request->send_headers(); 
  
          // Send the file
          $img = @ fopen($file, 'rb');
          if ($img) { 
              fpassthru($img); 
              exit; 
          } 
      }
  
  } // End Images
Usage
  echo Html::image('image/my_image.jpg');
how_to_serve_images_with_a_kohana_controller.txt · Last modified: 2010/01/02 13:26 by nanodocumet