Handling File Uploads in CakePHP

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 semicolonworld). 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/).

// src/Controller/HomeController.php

namespace App\Controller;

HomeController extends AppController
    public function 
// Include the FlashComponent
// Load Files model
// Set the layout
$this->layout 'frontend';
    public function 
$uploadData '';
        if (
$this->request->is('post')) {
$fileName $this->request->data['file']['name'];
$uploadPath 'uploads/files/';
$uploadFile $uploadPath.$fileName;
$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.'));
$this->Flash->error(__('Unable to upload file, please try again.'));
$this->Flash->error(__('Unable to upload file, please try again.'));
$this->Flash->error(__('Please choose a file to upload.'));
$files $this->Files->find('all', ['order' => ['Files.created' => 'DESC']]);
$filesRowNum $files->count();


src/Model/Table/FilesTable.php model is used to get and insert the file information into the database.

// src/Model/Table/FilesTable.php

namespace App\Model\Table;


FilesTable extends Table
    public function 
initialize(array $config){


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/';

Related Articles

Comments 0