CakeDC Blog


File uploading, file storage and CakePHPs MediaView class

This article includes how to upload and store files, because I've seen a lot of discussion about that too, but if you're just interested in how to use the MediaView class scroll down.

Handling file uploads in CakePHP

First let's start with the required form, to create a file upload form all you have to do is this:

echo $form->create('Media', array('action' => 'upload', 'type' => 'file'));
echo $form->file('file');
echo $form->submit(__('Upload', true));


The "type" in the options of Form::create() takes post, get or file. To configure the form for file uploading it has to be set to file which will render the form as a multipart/form-data form.

When you submit the form now, you'll get data like this in $this->data of your controller:

[Media] => Array
[file] => Array
[name] => cake.jpg
[type] => image/jpeg
[tmp_name] => /tmp/hp1083.tmp
[error] => 0
[size] => 24530

Ok, now the big question with a simple answer is where the file data should be processed, guess where. Right – in the model because it's data to deal with and validation to do against it. Because it's a recurring task to upload files I suggest you to write a behaviour for it or convert your existing component to a behaviour.

If you keep it generic you can extend it with a CsvUpload, VideoUpload or ImageUpload behaviour to process the file directly after its upload or do special stuff with it, like resizing the image or parsing the csv file and store its data in a (associated) model.

We're not going to show you our own code here for obvious reasons, but I'll give you a few hints what you can or should do inside of the behavior:

  1. Validate the uploaded field, the field itself contains already an error code if something was wrong with the upload. Here is a link to the php manual page that shows you the list of the errors that you can get from the form data.
  2. Validate the uploaded file, is it really the kind of file you want and does it really contain the data structure you want?
  3. Check if the target destination of the file is writeable, create directories, whatever is needed and error handling for it, I suggest you to use CakePHP's File and Folder classes for that.
  4. Add a callback like beforeFileSave() and afterFileSave() to allow possible extending behaviors to use them.

Database vs file system storage

Feel free to skip that part if you already store the files in the file system.

Storing files in the database is in nearly all cases a bad solution because when you get the file it has to go its way through the database connection, which can, specially on servers that are not in the same network, cause performance problems.

Advantages of storage in the file system:

  1. Easy and direct file access, to parse them (csv, xml...) or manipulate them (images)
  2. You don't need to install any additional software to manage them
  3. Easy to move and mount on other machines
  4. Smaller then stored in a DB

The suggested solution is to store meta data of the file like size, hash, maybe path and other related info in a DB table and save the file in the file system.

Some people come up with the security and want to store a file because of that in the database which is wrong. You should not store the file in a public accessible directory like the webroot of the application. Store it in another location like APP/media. You control the access to the file by checking the permissions against the DB records of your meta data and sending it by using the CakePHP MediaView class, I'll explain later how to use it.

I don't say that storage of files inside the DB is in general a bad idea but for web based applications it is in nearly every case a bad idea.

File system Performance

A bottleneck in the long run on every file system is a large amount of files in a single directory. Imagine just 10.000 users and each has an individual avatar image. Further ext3 for example is limited to 32000 sub folders, other file systems have maybe similar restrictions. You can find a list of file system limitations here:

To avoid performance problems caused by that you should store your files in a pseudo-random directory structure like APP/media/32/a5/3n/. This will also allow you to easily mount some of the semi-random created directories on another machine in the case you run out of disk space.

 * Builds a semi random path based on the id to avoid having thousands of files
 * or directories in one directory. This would result in a slowdown on most file systems.
 * Works up to 5 level deep
 * @see
 * @param mixed $string
 * @param integer $level
 * @return mixed
 * @access protected
	protected function _randomPath($string, $level = 3) {
		if (!$string) {
			throw new Exception(__('First argument is not a string!', true));

		$string = crc32($string);
		$decrement = 0;
		$path = null;
		for ($i = 0; $i < $level; $i++) {
			$decrement = $decrement -2;
			$path .= sprintf("%02d" . DS, substr('000000' . $string, $decrement, 2));

		return $path;

You should also know that php running in safe mode does not allow you to create more then one directory deep in one call. You have to take this in consideration, the above function does not cover that because safe mode is basically deprecated and will be also removed in php6

Sending a file to the client – or the unknown MediaView class

From what I've seen in the ruins of outsourced projects that asked us for rescue and also in the CakePHP googlegroup I think not many people are aware that CakePHP has a view that is thought to be used for downloads and display (images, text...) of files. It's called the MediaView class.

I'll now explain you how to use this class to send files to the client.

 * Sends a file to the client
 * @param string $id UUID
 * @access public
	public function download($id = null) {
		$this->Media->recursive = -1;
		$media = $this->Media->read(null, $id);

		if (empty($media)) {
		$this->redirect('/', 404, true);
		$this->set('cache', '3 days');
		$this->set('download', true);
		$this->set('name', $media['Media']['slug']);
		$this->set('id', $media['Media']['filename']);
		$this->set('path', APP . 'media' . DS . $media['Media']['path']);
		$this->set('modified', $media['Media']['modified']);
		$this->set('mimeType', $media['Media']['mime_type']);
		$this->set('extension', $media['Media']['extension']);

		$this->view = 'Media';
		$this->autoLayout = false;
		if ($this->render() !== false) {
				array('Media.downloads' => 'Media.downloads + 1'),
				array('' => $id));

You simply have to set autoLayout to false and the view class to media.

$this->view = 'Media';
$this->autoLayout = false;

There are a few view variables to set to “configure” the file download or display. To control if you want to make the client downloading the file or to display it, in the case of images for example, you simply set 'download' to true or false;

	$this->set('download', true);

You can control the browser caching of the file by setting cache. Please not that you do not have to use caching if download is set to true! Downloads do not need caching.

	$this->set('cache', '3 days');

The next part might be a little confusing, you have “id” and “name”. Id is the actual file on your server you want to send while name is the filename under which you want to send the file to the client. “path” is the path to the file on the server.

	$this->set('name', $media['Media']['slug']);
$this->set('id', $media['Media']['filename']);
$this->set('path', APP . 'media' . DS . $media['Media']['path']);

If you want to send a mime type that does not already in the MediaView class you can set it.

	$this->set('mimeType', $media['Media']['mime_type']);

If you don't set it, the class will try to determine the mime type by the extension.

	$this->set('extension', $media['Media']['extension']);

Note that you have to set the extension to make it work and that the extension is attached to the filename! If you store the filename with an extension you have to break it up.

When everything is set you can check if render() was successfully and do whatever you want after that, for example count the download.

	if ($this->render() !== false) {
	array('Media.downloads' => 'Media.downloads + 1'),
	array('' => $id));

Closing words

I hope you enjoyed reading the article and it helped you improving your knowledge about CakePHP. Feel free to ask further questions by using the comment functionality. Have fun coding!

Latest articles

Create Google app for web oauth2 login step by step

Here's a step by step tutorial about how to create a web oauth2 app in Google dashboard.

  • Add some cool name for your new Google app project and click "Create"
  • Under "Library" section, create a new Google+ API project
  • Click "Enable" in the dashboard tab
  • Under "Credentials" menu, click "Oauth consent screen" tab and enter some cool name to be displayed to users when requesting their access to your application. Then click "Save".
  • Under "Credentials" menu, click "Create credentials" and select "Oauth client ID".
  • Now click "Web application" radio, and type your domain name and oauth callback
    • Under "Authorized Javascript origins", add your domain name:
    • Under "Authorized redirect URIs", add all the allowed callback url's to your application. For example if you are using CakeDC/Users Plugin, you'll need to add
  • Then click "Save"
  • Copy the Iauth client and secret id's into your application configuration
  • Be careful, some browsers will append blank spaces to the codes, remove any extra blank space (trim)
  • Ensure the API is enabled, you can test your application now and check there is "Traffic" displayed
  You have now a Google app configured to provide Oauth2 login to your web application. Enjoy!                  

Login with Google Oauth2 in CakePHP using CakeDC/Users Plugin

This article is inspired by this question in Stack Overflow and belongs to a series of articles describing the step by step tutorial to configure CakeDC Users Plugin with the most commonly used Oauth2 providers, in this case we'll configure Google login. We'll assume you have a working CakePHP application with no Auth configured yet.


Use composer to install the CakeDC Users Plugin and the required oauth2 providers To be able to configure the callbacks in Google dashboard, you'll need to create a virtual host for you application. You don't need a working domain name, you could use something like "" but Google requires a domain name (no localhost). composer require cakedc/users:@stable composer require league/oauth2-google:@stable Load it from your bootstrap.php file Plugin::load('CakeDC/Users', ['routes' => true, 'bootstrap' => true]); Run migrations to add 2 new tables: 'users' and 'social_accounts' bin/cake migrations migrate -p CakeDC/Users


Load the Component in your src/Controller/AppController.php public function initialize() { parent::initialize(); // // ... // $this->loadComponent('CakeDC/Users.UsersAuth'); }

Create a new Google application

<?php // /config/users.php file contents $config = [ 'Users.Social.login' => true, '' => 'CLIENT_ID_HERE', '' => 'SECRET_HERE', ]; return $config;
  • Modify your bootstrap.php file to ensure the config file is loaded this way
Configure::write('Users.config', ['users']); //add this line before Plugin::load('CakeDC/Users... Plugin::load('CakeDC/Users', ['routes' => true, 'bootstrap' => true]); This file will override any configuration key present in the Plugin, you can check the configuration options here Configuration. Now you are ready to go to your login page and click "Sign up with Google". Upon successful login, a new user will be created in your users table and related oauth2 tokens will be saved in the social_accounts table. The new user created will have the "user" role (by default, but customizable). And based on your Auth rules, this user will be able to access your site. You are done!

Read more about CakeDC Users Plugin

Giving back to the community

This Plugin's development has been sponsored by the Cake Development Corporation. Contact us if you are interested in: We hope you've enjoyed this short tutorial covering the Google login, stay tunned for new CakePHP + Users Plugin tutorials coming soon...

Towards Data Integrity: Validations and Behaviors in CakePHP 3.0

Let us consider “validation” in a little more detail to see how it has been implemented and optimized in CakePHP 3.0. In addition to what we discussed in the earlier sections, validation now incorporates two complementary conceptions or areas. These include 1) data type and format validation and 2) Application rules. 1. Data Type and Format Validation This part of the validation deals structural aspects such as data type, format validation, and basic types. Unlike in previous versions, validation is applied before ORM entities are created. This is a very useful feature that ensures everything is totally in sync and set in a way that preserves data integrity and the overall stability of the entire application. Moreover, it markedly reduces application errors and inconsistencies throughout the system. It is therefore a significant enhancement over previous versions. 2. Application Rules Application rules are the second component of validation in CakePHP 3.0 implementation. They play a key role in quality control to ensure that all application rules and workflows are operating in an orderly and systematic fashion. This is implemented through buildRules() method in tables. Here is a code example that uses buildRules() method for articles table. // In src/Model/Table/ArticlesTable.php namespace App\Model\Table; use Cake\ORM\Table; use Cake\ORM\RulesChecker; class Articles extends Table {     public function buildRules(RulesChecker $rules)     {         $rules->add($rules->existsIn('user_id', 'Users'));         $rules->add(             function ($article, $options) {                 return ($article->published && empty($article->reviewer));             },             'isReviewed', [                 'errorField' => 'published',                 'message' => 'Articles must be reviewed before publishing.'             ]         );         return $rules;     } } Identifier Quoting Identifier quoting is another CakePHP feature or process that has changed in CakePHP 3.0. In the new release, quoted identifiers, which were expensive and involved a notoriously error-prone process of parsing SQL snippets has been disabled by default - thereby removing a major source of frustration for developers. The only time you may want to enable identifier quoting is when working with column names or table names with special characters or reserved words. Here is how to enable identifier quoting when configuring a connection. // In config/app.php 'Datasources' => [     'default' => [         'className' => 'Cake\Database\Driver\Mysql',         'username' => 'root',         'password' => 'super_secret',         'host' => 'localhost',         'database' => 'cakephp',         'quoteIdentifiers' => true     ] ],
Note: Identifiers in QueryExpression objects require manual quoting or IdentifierExpression objects.   Updating Behaviors Let us now turn to behaviors. As with most features that has to do with ORM, the way behaviors are setup and configured has evolved for smooth integration with the new framework. Among other things, behaviors now attach to table instances. Here are some other significant differences in the way behaviors are handled in CakePHP as compared to earlier versions. 1. Each table that uses a behavior will have its own instance. No storing of “name space” setting in a behavior is required. 2. Method signature for mixin, callback, and base class for behaviors have all changed 3. Finder methods can now be added easily by behaviors.   The above, in a nutshell, summarizes the main changes and enhancements in the new ORM and CakePHP 3.0 in general. Like all major releases or upgrades, the new release supplants many processes and functions in previous versions while at the same time adding many brand new features. But as you go through the initial learning curve, please remember that you, the developer, have been the primary driving force behind the changes and enhancements. Your feedback and critiques over the years was the invaluable source that inspired CakePHP team to produce this groundbreaking and cutting-edge release that you are reviewing.

We Bake with CakePHP