CakePHP does not provide any library to upload files. We need to use PHP’s move_uploaded_file()
function to upload file to the server. In this tutorial, you’ll learn how to upload a file in CakePHP. This article will cover the following functionalities in CakePHP 3.
To store the uploaded file information, create a table (for example files
) into the database (for example codexworld
). The SQL of basic table structure to keep file information will something like the below.
CREATE TABLE `files` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `path` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `created` datetime NOT NULL, `modified` datetime NOT NULL, `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1 = Active, 0 = Inactive', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
In this example script, we’ll use the src/Controller/HomeController.php
controller to demonstrate file upload process.
Files model is loaded in the initialize()
function that will help to insert the file information into the database.
index()
function is responsible for showing the file uploading form and the uploaded files list. move_uploaded_file()
function is used to upload the file to the folder (webroot/uploads/files/
).
<?php
// src/Controller/HomeController.php
namespace App\Controller;
class HomeController extends AppController
{
public function initialize(){
parent::initialize();
// Include the FlashComponent
$this->loadComponent('Flash');
// Load Files model
$this->loadModel('Files');
// Set the layout
$this->layout = 'frontend';
}
public function index(){
$uploadData = '';
if ($this->request->is('post')) {
if(!empty($this->request->data['file']['name'])){
$fileName = $this->request->data['file']['name'];
$uploadPath = 'uploads/files/';
$uploadFile = $uploadPath.$fileName;
if(move_uploaded_file($this->request->data['file']['tmp_name'],$uploadFile)){
$uploadData = $this->Files->newEntity();
$uploadData->name = $fileName;
$uploadData->path = $uploadPath;
$uploadData->created = date("Y-m-d H:i:s");
$uploadData->modified = date("Y-m-d H:i:s");
if ($this->Files->save($uploadData)) {
$this->Flash->success(__('File has been uploaded and inserted successfully.'));
}else{
$this->Flash->error(__('Unable to upload file, please try again.'));
}
}else{
$this->Flash->error(__('Unable to upload file, please try again.'));
}
}else{
$this->Flash->error(__('Please choose a file to upload.'));
}
}
$this->set('uploadData', $uploadData);
$files = $this->Files->find('all', ['order' => ['Files.created' => 'DESC']]);
$filesRowNum = $files->count();
$this->set('files',$files);
$this->set('filesRowNum',$filesRowNum);
}
}
src/Model/Table/FilesTable.php
model is used to get and insert the file information into the database.
<?php
// src/Model/Table/FilesTable.php
namespace App\Model\Table;
use Cake\ORM\Table;
class FilesTable extends Table
{
public function initialize(array $config){
$this->addBehavior('Timestamp');
}
}
src/Template/Home/index.ctp
view is responsible for creating the upload form and display the uploaded files list.
The following code will render the file upload form in CakePHP.
<h1>Upload File</h1> <div class="content"> <?= $this->Flash->render() ?> <div class="upload-frm"> <?php echo $this->Form->create($uploadData, ['type' => 'file']); ?> <?php echo $this->Form->input('file', ['type' => 'file', 'class' => 'form-control']); ?>
<?php echo $this->Form->button(__('Upload File'), ['type'=>'submit', 'class' => 'form-controlbtn btn-default']); ?>
<?php echo $this->Form->end(); ?> </div> </div>
The following code will display the uploaded files list. Here you can see, HTML <embed> Tag is used to display the preview of the uploaded files.
<h1>Uploaded Files</h1> <div class="content"> <!-- Table --> <table class="table"> <tr> <th width="5%">#</th> <th width="20%">File</th> <th width="12%">Upload Date</th> </tr> <?php if($filesRowNum > 0):$count = 0; foreach($files as $file): $count++;?> <tr> <td><?php echo $count; ?></td> <td><embed src="<?= $file->path.$file->name ?>" width="220px" height="150px"></td> <td><?php echo $file->created; ?></td> </tr> <?php endforeach; else:?> <tr><td colspan="3">No file(s) found......</td> <?php endif; ?> </table> </div>
Create the directory (webroot/uploads/files/
) where you want to store the uploaded files and assign the upload directory path in $uploadPath
variable.
$uploadPath = 'uploads/files/';
Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request
wow…its working thank you so much..
i was searching for this code from last 3-4 days…and this works …thank so much from the bottom of my heart
how did it differentiate between image file and any other file?
WOW so nice after trying this with so many other tutorial. This finally worked
Thanks you so much! I hope you will given us other useful examples.
Thanks a lot, this is the best Cakephp3 tutorials.
I’m studying CakePHP and it’s difficult for me understand it. Your article made it simple. Thanks!
hello dears i have completed steps for upload a file from here.but i want to download that particular file which is uploaded like as upload/files(path).so please help me how i download that file.
can you please guide me to how to insert multiple input value with file?
here no download file link.How we download a particular uploaded file. please help me.give me advics this topic in cakephp 3
Thanks for this share. I have looking for such codes as I am developing a site using CakePHP and facing such development issues.