Example – 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 codexworld). The SQL of basic table structure to keep file information will something like the below.


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/Model/Table/FilesTable.php model is used to get and insert the file information into the database.


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.

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.

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.

Leave A Reply

Your email address will not be published.