File upload in CakePHP 3 using Cake Bake

File Upload CakePHP 3

In our last article, we explained how to use cake bake command for a basic CakePHP application. There is no CakePHP internal library to upload files, so we need to use core PHP’s function move_uploaded_file() to upload file/files to the server. In this article, we will let you know how to upload a file in CakePHP.

Let’s start doing it from the very basic steps

Step 1. Database Setup – Firstly likewise our previous article (http://www.qualitians.com/create-a-small-cakephp-application-using-cakebake/) create a database “cakephp” and then a tables under it as follows.

Database: cakephp
Tables: users, types, countries

CakePHP Cakebake Tables

CakePHP Cakebake Tables

Users Table:

Users Table for File Upload in CakePHP 3

Users Table for File Upload in CakePHP 3

Note: Important point to note here is that we have created a new field with the name “file” with “varchar” datatype to store file name which will be uploaded by the user.

Types Table:

CakePHP CakeBake Types Tables

CakePHP CakeBake Types Tables

Countries Table:

CakePHP CakeBake Countries Tables

CakePHP CakeBake Countries Tables

Step 2. Open up your terminal window to run cake commands and get into the cakephp directory with the command

cd /var/www/html/CakePHP;

Step 3. As we are having 3 tables, so we have to use the following commands one by one. This will show you “Bake All Complete”

bin/cake bake all users;
bin/cake bake all types;
bin/cake bake all countries;

Step 4.  In your browser, type “http://localhost/CakePHP/users” and check the “file field”. Currently this will be in input type text but we will modify it as per our needs in the next steps.

Step 5. Create uploads directory webroot/uploads/files/ and now, go to “cakePHP/src/Template/Users/add.ctp” and replace

<!-- Remove code -->
<?= $this->Form->create($user) ?> 

<!-- Add code to create multipart/form-data -->
<?= $this->Form->create($user, ['type' => 'file']) ?>
<!-- Remove code -->
echo $this->Form->input('file'); 

<!-- Add the updated code to allow file upload -->
echo $this->Form->input('file', ['type' => 'file', 'class' => 'form-control']);

this will change the text file input field to file uploading browse button.

Step 6. Open “UsersController.php” and edit add() function as follows

public function add()
{
    $user = $this->Users->newEntity();
    if ($this->request->is('post'))
    {
        //Start - Controller Code to handle file uploading
        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))
            {
	        $this->request->data['file'] = $uploadFile;
            }
        }
        //End 	
        $user = $this->Users->patchEntity($user, $this->request->data);
        if ($this->Users->save($user))
        {
            $this->Flash->success(__('The user has been saved.'));
            return $this->redirect(['action' => 'index']);
        }
        $this->Flash->error(__('The user could not be saved. Please, try again.'));
    }
    $types = $this->Users->Types->find('list', ['limit' => 200]);
    $countries = $this->Users->Countries->find('list', ['limit' => 200]);
    $this->set(compact('user', 'types', 'countries'));
    $this->set('_serialize', ['user']);
}

Step 7. Open “cakePHP/src/Template/Users/edit.ctp” and make the changes same as that of “add.ctp”

<!-- Remove code -->
<?= $this->Form->create($user) ?> 

<!-- Add code to create multipart/form-data -->
<?= $this->Form->create($user, ['type' => 'file']) ?>
<!-- Remove code -->
echo $this->Form->input('file'); 

<!-- Add the updated code to allow file upload -->
echo $this->Form->input('file', ['type' => 'file', 'class' => 'form-control']);

Step 8. In browser, type “http://localhost/cakePHP/users/add” and add a new user along with his details and his file/picture.

Step 9. Go to “http://localhost/cakePHP/users” and click on “View” of any entry of user to check the details filled for user profile. OR you can also use the image tag in “src/Template/Users/view.ctp” to show the image saved.

File Upload CakePHP 3

File Upload CakePHP 3

You may also like...

2 Responses

  1. des stof says:

    Thank you for sharing your knowledge – it means a lot to me as a newbie to Cake 3. I will test and comment.

Leave a Reply