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:


That will redirect the app to 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.

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

The post How To Set Up CakePHP For Production: Ubuntu 16.04 appeared first on Low End Box.

How To Install CakePHP On Ubuntu 16.04 VPS

How To Install CakePHP On a Ubuntu 16.04 VPS

With this tutorial, you will be able to create a CakePHP environment from scratch, define a database, and automatically generate a working web app.

You will start with an empty black screen and within an hour have a small web site on a VPS.

What are we going to cover

  • installation of LAMP stack (Linux, Apache, MySQL, PHP),
  • creation of user which will have access to the app,
  • installation of CakePHP itself,
  • creation of the database for the app,
  • creation of the app itself, through the process known as baking.


We shall install and deploy CakePHP on Ubuntu 16.04:

  • Starting with a clean VPS with
  • At least 512Mb of RAM and
  • 15Gb of free disk space.
  • You will need root user access

Step 1: Creating a Non Root User

Once you are logged in as root, you can create a new user account that you’ll use from now on. Root is useful for performing system administration tasks, but using it for ordinary tasks is error prone and risky.

We’ll call the new user cakeuser. To create it, run:

adduser cakeuser

Then, add it to the sudo group, so that you can run commands as sudo:

usermod -aG sudo cakeuser

Step 2: Install Apache

First, update your package manager’s cache:

sudo apt update -y

Install the Apache web server:

sudo apt install apache2 -y

Next, enable its service to make it run on every system boot:

sudo systemctl enable apache2

Finally, start it:

sudo systemctl start apache2

To verify that Apache was installed successfully, access it from your local browser by navigating to http://SERVER_IP/. If that does not work, try adding :80 in the end, like this:


You should see a welcome page for Apache, which means that you now have Apache running.

Step 3: Install MySQL Database

To install MySQL database, run the following command:

sudo apt install mysql-server -y

This will install the MariaDB database server (an enhanced fork of MySQL). You will be asked to enter a password for the MySQL root user. (Use Tab key from the keyboard to switch to the OK button and press Enter on the keyboard.)

Then secure MySQL installation by running:

sudo /usr/bin/mysql_secure_installation

Depending on the level of security you wish to achieve, you’ll have the option to adjust the minimum password complexity. Press 2 to select the highest level. Answer y to every prompt you get afterwards.

So you enter one password first, to enable access to MySQL, then ener another password to secure the installation. Store that second password as you will need it in Step 9 of this article.

To make it run on every system boot, enable it via systemctl:

sudo systemctl enable mysql

Step 4: Install PHP

Finally, install PHP by running:

sudo apt install php -y

This will install PHP 7.0, which will here serve just fine.

You’ll then need to install common PHP extensions that CakePHP requires:

sudo apt install php-{bcmath,bz2,intl,gd,mbstring,mcrypt,mysql,zip,intl,xml} libapache2-mod-php unzip -y

Linux uses tar to decompress files while some of the files for PHP come in zip format, so the above line will install zip and unzip programs as well.

Step 5: Install Composer

Composer is a flexible PHP package manager, which CakePHP uses to manage all of its dependencies.

Install curl to download the install script for Composer:

sudo apt install curl -y

Then, download the installer:

cd ~
sudo curl -s | php

To make it available globally, move it to /usr/bin:

sudo mv composer.phar /usr/local/bin/composer

You are installing Composer as root user and it will show a warning about it. Once we have the app installed, we shall give access to its folder to user cakeuser.

Step 6: Create an Example CakePHP App

Apache stores the data it serves under /var/www/html. To create a new app, run:

composer create-project --prefer-dist cakephp/app /var/www/html/cakeapp

Here “cakeapp” will be the name of the app. You may install several CakePHP apps in this way on the same server, just change “cakeapp” for the new name.

When Composer asks if you want it to set up folder permissions, answer with y.

If for some reason you later get a warning that these folders are not accessible, you may run these two commands:

sudo chmod -R a+rw /var/www/html/cakeapp/logs
sudo chmod -R a+rw /var/www/html/cakeapp/tmp

In Step 11 of this tutorial we shall use bake command in CakePHP to create a ready made app. For now, let us create a permission to access it:

cd /var/www/html/cakeapp
chmod +x bin/cake

We can now give user cakeuser access to the app folder:

sudo chown -R cakeuser /var/www/html/cakeapp

Have your passwords always easily accessible as Ubuntu will ask you for them whenever you change or access something in the system.

Step 8: Configuring Apache

Edit Apache configuration file so that it will serve CakePHP app by default. It is called 000-default.conf and is stored in directory /etc/apache/sites-enabled. Open it for editing:

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

Find line which starts with DocumentRoot and replace it with this:

DocumentRoot /var/www/html/cakeapp/webroot

Save and close the file.

CakePHP requires Apache module_rewrite to also be enabled; do so by running:

sudo a2enmod rewrite

Finally, instruct Apache to use .htaccess files, with which CakePHP configures Apache on the fly. Open Apache global configuration file for editing:

sudo nano /etc/apache2/apache2.conf

Under the block, you’ll find the following line:

AllowOverride None

Change it to

AllowOverride All

When you are done, save the file.

Again restart Apache so that it takes new configuration into account:

sudo systemctl restart apache2

You can now navigate to your domain in your browser. You should see the following:

CakePHP is now installed properly, save for the fact that there is no database to connect to. We shall first create the database and then connect it to CakePHP in the next step.

Step 9 – Creating a Database

Launch MySQL shell:

sudo mysql -u root -p

When asked, enter the second password from Step 3 of this tutorial.

Once in MySQL prompt, copy and paste the following code as a whole, then press Enter on the keyboard:

USE blogdb;
    title VARCHAR(50),
    body TEXT,
    INSERT INTO posts (title, body, created)
    VALUES ('Sample title', 'This is the article body.', NOW());
    GRANT ALL PRIVILEGES ON blogdb.* TO 'post_user'@'localhost' IDENTIFIED BY 'password9I%';

That will execute everything at once. Here is what it will look like in the terninal:

The first line will create a database blogdb and from the second line on, will start using it. Then we create table called posts with two visible fields, title and body. Columns id, created, and modified are necessary but will be used by CakePHP only internally.

Then we populate table posts by inserting one sample value.

The next line, starting with GRANT ALL PRIVILEGES is crucial. It creates a new user called _postuser and grants it all privileges on database blogdb. Currently there is only one table in this database, posts.

The third part, starting with IDENTIFIED BY, defines the password. It must contain lower and uppercase letters, as well as digits and special characters. Be sure to always change and invent new passwords for database users.

Command FLUSH PRIVILEGES; reloads the database with the changes made. The last command is EXIT, to leave the MySQL prompt and go back to the command line in Ubuntu itself.

Step 10: Connecting App to the Database

Navigate to the app folder:

cd /var/www/html/cakeapp/

CakePHP stores database credentials in a file named app.php, stored under the config folder. Open it for editing:

sudo nano /var/www/html/cakeapp/config/app.php

Find the Datasources block:

    'Datasources' => [
        'default' => [
            'className' => 'CakeDatabaseConnection',
            'driver' => 'CakeDatabaseDriverMysql',
            'persistent' => false,
            'host' => 'localhost',
            //'port' => 'non_standard_port_number',
            'username' => 'post_user',
            'password' => 'password9I%',
            'database' => 'blogdb',

In your terminal it may look like this:

For ‘username’ put your database user’s user name (post_user), for ‘password’ put your database user’s password (password9I%), and for database name it is obvious what to put (blogdb).

Save and close the file.

Refresh app in your browser and observe the success message under the Database section.

Step 11: Creating Your First CakePHP App

Under normal circumstances, you would have to now learn programming in PHP, then learn CakePHP, and within a couple of days, weeks or months, you would have your first “Hello World” app on the server.

There is a much faster way – using the bake command. Execute this:

./bin/cake bake all posts

It will create CakePHP code in various folders and produce an app that can read, save, update and delete entries in table posts of database blogdb.

Part of the bake output is shown here:

Visit the address in the browser:


That’s it, we now have a CakePHP app installed, connected to the database and running for real.

What To Do Next

Now you have a rudimentary CakePHP app on your server. The rest depends on your original intentions. For example, if you are a developer selling sites to the clients, at this point you can upload your CakePHP app and be sure that it will run properly.

Once you finish your app, see article “How To Set Up CakePHP For Production: Ubuntu 16.04” how to improve your site before going to production phase.

Dusko Savic is a technical writer and Flutter programmer.

The post How To Install CakePHP On Ubuntu 16.04 VPS appeared first on Low End Box.