Simplest way for File handling in CakePHP 3

In this article, we are going to cover a best way for files handling in cakephp 3. In CakePHP, do not have any library for uploading files. So, we'll have to use PHP method i.e. move_uploaded_file for uploading files to the server.

Here, we have explained steps to use this method i.e. move_uploaded_file inside cakephp project. These steps will cover a short example script of cakephp 3 project including file uploading functionality. In this example, we have created user profile module.

Step 1: Database Table

To store the user profile information, we have to create table i.e. users in database. This table will store user information like name, email, picture etc. Here is sql script to create user table.

CREATE TABLE `users` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `name` varchar(255) COLLATE utf8_general_ci NOT NULL,
    `email` varchar(255) COLLATE utf8_general_ci NOT NULL,
    `profile_pic_name` varchar(512) COLLATE utf8_general_ci  NOT NULL,
    `profile_pic_path` varchar(512) COLLATE utf8_general_ci  NOT NULL,
    `created` datetime NOT NULL,
    `modified` datetime NOT NULL,
    PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;

Step 2: User Picture Directory

To store user's profile picture, create the directory i.e. profile at path i.e. /webroot/uploads/files/. To avoid errors during functionality, please make sure directory i.e. /webroot/uploads/files/profile is having full permission.

Step 3: Controller

This step will cover the logical part of functionality i.e. user profile. We have to create Users Controller i.e. src/Controller/UsersController.php to demonstrate Add New User functionality including upload profile picture feature. In this controller, we have created a add method which will be call by url i.e. [Your_Domain_Name]/users/add. Here is code of user controller :

request->is('post')) {
            if(!empty($this->request->data['profile_pic']['name'])){
                $profile_pic_name = $this->request->data['profile_pic']['name'];
                $profile_pic_path = 'uploads/files/profile/';
                $profile_pic_file = $profile_pic_path.$profile_pic_name;
                if(move_uploaded_file($this->request->data['profile_pic']['tmp_name'],$profile_pic_file)){
                    $userData = $this->Users->newEntity();
                    $userData->name = $this->request->data['user_name']
                    $userData->email = $this->request->data['user_email']
                    $userData->profile_pic_name = $profile_pic_name;
                    $userData->profile_pic_path = $profile_pic_path;
                    $userData->created = date("Y-m-d H:i:s");
                    $userData->modified = date("Y-m-d H:i:s");
                    if ($this->Users->save($userData)) {
                        $this->Flash->success(__('User has been created successfully.'));
                    }else{
                        $this->Flash->error(__('Unable to create user, please try again.'));
                    }
                }else{
                    $this->Flash->error(__('Unable to upload user profile pic, please try again.'));
                }
            }else{
                $this->Flash->error(__('Please choose user profile pic to upload.'));
            }
        }
        $this->set('userData', $userData);
    }
}

Step 4: Model

This step will cover the database part of functionality i.e. user profile. We have to create Users Model i.e. src/Model/Table/UsersTable.php for getting and inserting the new user information into the database. Here is code of user model :

addBehavior('Timestamp');
    }
}

Step 5: View

This step will cover the view part of functionality i.e. user profile. We have to create ctp file inside users template folder i.e. src/Template/Users/add.ctp for building create new user form. This template will render on call of this url i.e. [Your_Domain_Name]/users/add. Once this form will submit, this will call add method with post parameters for implementation of business logic. Here is code of add user template :

Add New User

Flash->render() ?>
Form->create($userData, ['type' => 'file']); // Full Name of User echo $this->Form->control('user_name', array('label' => 'Full Name of User', 'required'=>true,'class'=>'form-control')); // Email of User echo $this->Form->control('user_email', array('label' => 'Email of User', 'required'=>true,'class'=>'form-control', 'type'=>'email')); // Profile Picture of User echo $this->Form->input('profile_pic', ['type' => 'file', 'class' => 'form-control']); // Submit Button echo $this->Form->button(__('Create User'), ['type'=>'submit', 'class' => 'form-control btn btn-default']); echo $this->Form->end(); ?>

Here, you are ready with functionality of file handling in Cakephp 3. Explore and modify it as per your requirement.