File Handling Uploads using in CakePHP Framework

CakePHP does not give any library to transfer records. We have to utilize PHP’s move_uploaded_file() capacity to transfer record to the server. In this instructional exercise, you’ll figure out how to transfer a record in CakePHP. This article will cover the accompanying functionalities in CakePHP 3.

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

Mysql Database Table Creation
To store the uploaded file information, create a table into the Mysql database. The SQL of basic table structure to keep file information will something like the below.

1
2
3
4
5
6
7
8
9
CREATE TABLE `queryfiles_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/).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
<?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.

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.

1
2
3
4
5
6
7
8
9
10
<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 Tag is used to display the preview of the uploaded files.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<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 ($root.’/webroot/uploads/files/’) where you want to store the uploaded files and assign the upload directory path in $uploadPath variable.

Leave a Reply

Your email address will not be published. Required fields are marked *