Srilatha Marru's Blog
Cakephp relative file path

In cakephp relative file paths are little tricky. Unless they are defined in the routes or in the actions/functions a file will not be rendered as you are expecting it to.   So many a times  or always you can use absolute paths to point to a file like an image or a video.

In  my scenario using the relative paths for a file was mandatory.  I was given a pre compiled swf file with relative paths encoded in it.  And the cakephp didn’t understand the filename in the url as it was.  So here is what I found in cakephp documentation which solved my problem of rendering the relative urls.

Media Views (From Cakephp site):

Media views allow you to send binary files to the user. For example, you may wish to have a directory of files outside of the webroot to prevent users from direct linking them. You can use the Media view to pull the file from a special folder within /app/, allowing you to perform authentication before delivering the file to the user.

To use the Media view, you need to tell your controller to use the MediaView class instead of the default View class. After that, just pass in additional parameters to specify where your file is located.

 class ExampleController extends AppController {
function download () {
$this->view = 'Media';
$params = array(
'id' => '',
'name' => 'example',
'download' => true,
'extension' => 'zip',
'path' => APP . 'files' . DS

Hope you will find it useful too and will save your time.


profileWeb Developer working in advertising agency.

Recent tweets

The Twitter REST API v1 is no longer active. Please migrate to API v1.1.