Sunday, February 13, 2022

[FIXED] CakePHP 3 - Downloading regardless of the host and project name

Issue

On any particular View, if I include this link:

<?php echo $this->Html->link('Download', ['controller' => 'Uploads', 'action' => 'download',$upload->id]) ?>

A user can download a file based on the $upload->id provided.

I'm using this as my download function in my Uploads controller:

$upload = $this->Uploads->find('all')->first();
$filePath = '\xampp\htdocs\project\webroot\uploads'; //file path to where the uploaded file is
$this->response->file($filePath . DS . $upload->name,
    array('download' => true, 'name' => $upload->name)); //finds the corresponding name attribute in the Uploads table of the database, finds a matching name in the uploads directory and then downloads that file.

$this->set(compact('upload'));

However, I was wondering if there was a way to be able to have the file path be more flexible. In my config.php, I have set two variables called $host and $basepath to refer to the web host (localhost) and the project name (project) respectively. I pass these variables to the AppController, and they can be accessed by any View.

But I can't seem to use these variables in the $filePath variable of the download function, so if I or anyone else were to change hosts or the project name, instead of being able to simply change config.php, I or anyone else would have to go and find this and change it as well (and if I had multiple download functions in multiple controllers, they'd have to go and change each and every one of them).


Solution

Take a look at the CakePHP global constants. You can easily access the path to your webroot by using WWW_ROOT.

https://book.cakephp.org/3.0/en/core-libraries/global-constants-and-functions.html



Answered By - Marijan

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.