Handling File Uploads in CakePHP

cakephp-file-upload-by-codexworld

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.

  • File upload form creation.
  • File upload to the server.
  • Store the uploaded file information into the database.

Database Table Creation

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;

Controller

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);
    }
    
}

Model

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');
    }
}

View

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>

Upload Directory

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

11 Comments

  1. Akky Said...
  2. Shashi Said...
  3. Ansu Said...
  4. Ehis Said...
  5. Tien Pham D. Said...
  6. Yuri Said...
  7. Rodrigo Said...
  8. Mandeep Said...
  9. Jay Said...
  10. Mandeep Said...
  11. Talentelgia Said...

Leave a reply

keyboard_double_arrow_up