LowEndBox - Cheap VPS, Hosting and Dedicated Server Deals

How To Set Up CakePHP For Production: Ubuntu 16.04

How To Set Up CakePHP For Production: Ubuntu 16.04

We shall assume that you have developed a CakePHP app on the server and that you are going to launch it as a product. To bring your app to the production level, you’ll need to

  • Clean up the code,
  • Increase security by enabling Security and CSRF components, and
  • Set up the app on the server correctly.

Cleaning Up the Code

Disable Debug Mode

Every installation of CakePHP comes with the Debug mode enabled and virtually all programmers use it. Debug mode set to false is the way to go in production, to prevent leaking of sensitive info.

To disable Debug mode, open the config file for editing:

sudo nano config/app.php

and find the line where the debug variable is mentioned, at the top of the file. Set its value to false, like this:

'debug' => filter_var(env('DEBUG', false), FILTER_VALIDATE_BOOLEAN),

Save the file and refresh the site in your browser. In case you have a brand new app, this is the screen you are going to see:

This page, located under src/Template/Pages/home.ctp, is the homepage. This is the place to introduce the site or redirect the user to another page. The following code will save the existing home.ctp file, in case you want to bring it back later, and will create an empty file so that you can put the appropriate code into it.

Execute this from command line:

cd /var/www/html/cakeapp/src/Template/Pages/
mv home.ctp home_old.ctp
touch home.ctp
sudo nano /var/www/html/cakeapp/src/Template/Pages/home.ctp

Command mv renames the existing file, touch creates a new file with the same name, only empty. It then opens the editor so you can put the following code into it:

echo '<script>window.location='https://google.com';</script>

That will redirect the app to Google.com but in real life, you will redirect it to one of the pages on your own site.

Setting Up Passwords in SetEnv Variables

Environment variables on Apache HTTP Server store information in named variables that are available in PHP and CakePHP code. Normal usage of environment variables would be to control logging or access to certain pages on the site. You can also set a value for Debug as SetEnv and dynamically check it in the app. The following goes to the Apache configuration file:


and then you can check it out in the app.php file:

$debug = (bool)getenv('CAKEPHP_DEBUG');
return [
    'debug' => $debug,

SetEnv can also store sensitive data such as passwords. Then, the passwords would be available in code, but not through text in source code of the app, which adds another level of security.

Clear the Cache Before You Begin

Cached files in CakePHP may reach hundreds of MB and will slow the app down. Before you go to production, be sure to execute this command from your app directory:

bin/cake schema_cache clear

You should also issue this command whenever you change any data structure in any of the databases and tables, otherwise CakePHP will not take them into account.

NOTE: Once in production, use the Migration tool to change database schemas.

Models Should Have the Correct Validation Rules Enabled

Model classes in directory /Model/Table contain code for logic validation of input in forms. There will be two functions in those files, validationDefault and buildRules and here is what they do.

validationDefault will have an entry like this:

            ->requirePresence('username', 'create')

which means that for input field called username, when you press Save on the Form, the field must not be empty. If it is empty, an error will be shown and the data will not be saved to the database, but will instead be presented to the user again.

buildRules may look like this:

        $rules->add($rules->existsIn(['user_id'], 'Users'));

isUnique means that the email address entered must be unique in the database and if there is a match, a message will be shown to the user and the form data will not be saved.

existsIn means that the value entered must be present in table Users and if it is not there, an error message will be shown and the form will not be saved.

You can turn off all these validators, by just commenting them out. Do it at your own risk, because it opens up the possibility of entering data in inappropriate formats.

Learn more about Validators from the official documenation page.

Improve Security of Your CakePHP App

Activate the Cross Site Request Forgery Component

Once in the wild, your app can become an object of attack, mostly by automated software. Cross Site Request Forgery is a common attack performed on web apps and if successful, can lead to the equivalent of online robbery.

The protection mechanism consists of adding a randomly generated token as a hidden field to every form, which the server knows. This way, the potential attacker has no means of knowing what the token might be, and the attack will fail.

As of version 3.5, CakePHP also implements CSRF protection as middleware.
You should either use CSRF as a component or as middleware, but not both at the same time.

Activate the Security Component

The Security component will enable you to:

  • Restrict which HTTP methods your application accepts
  • Prevent Form tampering
  • Require that SSL be used
  • Limit cross controller communication

Use it in your controller’s beforeFilter() call. Since Security can be used with other callbacks from there, it should be executed before them in the initialize() method.

The Security Component will automatically give you the means to fight form tampering protection. It inserts and then checks on hidden token fields that are automatically inserted into forms.

It will also work in conjunction with the SCRF component.

Where To Put Code to Activate Security Components

You may put all of your security components into the file AppController.php, as all other controllers will import that file automatically. Access it via

sudo nano /var/www/html/cakeapp/src/Controller/AppController.php

This is the beginning of the file and it may have additional lines of code in it.

namespace App\Controller;
use Cake\Controller\Controller;
use Cake\Event\Event;
class AppController extends Controller {
    public $components = ['Flash', 'Auth', 'Security', 'Csrf', 'Cookie']; 
    public $helpers = ['Form'];

Setting Up the App on the Server Correctly

Set Up DocumentRoot

If you have followed advice on installing and setting up your first CakePHP app, you will have set up this properly already. If not, open Apache default site config file for editing:

sudo nano /etc/apache2/sites-enabled/000-default.conf

and change the DocumentRoot like this:

DocumentRoot /var/www/html/cakeapp/webroot

If you are on shared hosting, it is not likely that you will be able to change DocumentRoot directly. Your only option may be to use basic html folder as the root of the app and for the details have a look here.

Take Care of the webroot Folder

Files and directories in webroot folder of your app are accessible to the rest of the Internet. If you want to store public images on the site, that’s where you can put them.

If you have old PHP code that is important to execute without change, you may put it in webroot subfolder as well. It will be executed outside of CakePHP, which means that someone can destroy your site without you ever noticing. If you must put a PHP file there, be sure never to execute it in the browser, or – even better – rewrite the old code to be compatible with CakePHP and then execute it in a normal Cake way.

Dusko Savic is a technical writer and Flutter programmer.


Dusko on LinkedIn

No Comments

    Leave a Reply

    Some notes on commenting on LowEndBox:

    • Do not use LowEndBox for support issues. Go to your hosting provider and issue a ticket there. Coming here saying "my VPS is down, what do I do?!" will only have your comments removed.
    • Akismet is used for spam detection. Some comments may be held temporarily for manual approval.
    • Use <pre>...</pre> to quote the output from your terminal/console, or consider using a pastebin service.

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