simple cakephp file upload functionality.

Here in this article we will discuss about  uploading files in cakephp framework.

Below is a simple cakephp file upload functionality.

Here for the explanation I am considering the Users view and created a new file named upload_file.ctp under app/views/users folder.

Add the below code in upload_file.ctp. This code creates a from for uploading the file with browse button.

<div class="users view">
<h2><?php echo __('User'); ?></h2>
echo $this->Form->create('uploadFile', array( 'type' => 'file'));
echo $this->Form->input('pdf_path', array('type' => 'file','label' => 'Pdf'));
echo $this->Form->end('Upload file');
$image_src = $this->webroot.'files/'.$image;
<!-- to display uploaded file ( considering uploaded file is a image) -->
<img src="<?php echo $image_src;?>">

Since I am using Users view, now  going to use UsersController to handle the uploaded file.

Add the below code in UsersController.php file which is placed in the app/Controllers folder. This code checks the uploaded file for the error and moves the uploaded file to the webroot/files folder.

 public function uploadFile() {
            $filename = '';
            if ($this->request->is('post')) { // checks for the post values
		$uploadData = $this->data['uploadFile']['pdf_path'];
                if ( $uploadData['size'] == 0 || $uploadData['error'] !== 0) { // checks for the errors and size of the uploaded file
                    return false;
                $filename = basename($uploadData['name']); // gets the base name of the uploaded file
                $uploadFolder = WWW_ROOT. 'files';  // path where the uploaded file has to be saved
                $filename = time() .'_'. $filename; // adding time stamp for the uploaded image for uniqueness
                $uploadPath =  $uploadFolder . DS . $filename;
                if( !file_exists($uploadFolder) ){
                    mkdir($uploadFolder); // creates folder if  not found
                if (!move_uploaded_file($uploadData['tmp_name'], $uploadPath)) {
                    return false;



Note : For explanation I have used User controller and User view. According to the requirement you can any view and controller.


Leave a Reply

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