Cakephp Classroom image

Anil  Bist / Professional / Web Technology

To post your Question Join Classroom
Lesson Topics's No:-  |1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9|Last
Lessons:-Getting Started

Getting Started

The CakePHP framework provides a robust base for your application. It can handle every aspect, from the user’s initial request all the way to the final rendering of a web page. And since the framework follows the
principles of MVC, it allows you to easily customize and extend most aspects of your application. The framework also provides a basic organizational structure, from filenames to database table names, keeping your entire application consistent and logical. This concept is simple but powerful. Follow the conventions and you’ll always know exactly where things are and how they’re organized. The best way to experience and learn CakePHP is to sit down and build something. To start off we’ll build a simple blog application.

Blog Tutorial

Welcome to CakePHP. You’re probably checking out this tutorial because you want to learn more about how CakePHP works. It’s our aim to increase productivity and make coding more enjoyable: we hope you’ll see
this as you dive into the code.

This tutorial will walk you through the creation of a simple blog application. We’ll be getting and installing CakePHP, creating and configuring a database, and creating enough application logic to list, add, edit, and delete blog posts.

Here’s what you’ll need:

  1. A running web server. We’re going to assume you’re using Apache, though the instructions for using other servers should be very similar. We might have to play a little with the server configuration, but most folks can get CakePHP up and running without any configuration at all. Make sure you have PHP 5.2.8 or greater.
  2. A database server. We’re going to be using MySQL server in this tutorial. You’ll need to know enough about SQL in order to create a database: CakePHP will be taking the reins from there. Since we’re using MySQL, also make sure that you have pdo_mysql enabled in PHP.
  3. Basic PHP knowledge. The more object-oriented programming you’ve done, the better: but fear not if you’re a procedural fan.
  4. Finally, you’ll need a basic knowledge of the MVC programming pattern. A quick overview can be found in Understanding Model-View-Controller. Don’t worry, it’s only half a page or so.

Getting CakePHP

First, let’s get a copy of fresh CakePHP code.

To get a fresh download, visit the CakePHP project on GitHub: and download the latest release of 2.0

You can also clone the repository using git4. git clone git://

Regardless of how you downloaded it, place the code inside of your DocumentRoot. Once finished, your directory setup should look something like the following:


Now might be a good time to learn a bit about how CakePHP’s directory structure works: check out the CakePHP Folder Structure section.

Tmp directory permissions

Next we’ll need to make the app/tmp directory writable by the webserver. The best way to do this is to find out what user your webserver runs as. You can run <?php echo exec('whoami'); ?> inside any PHP file your webserver can execute. You should see a username printed. Change the ownership of the app/tmp directory to that user. The final command you run (in *nix) might look something like this:

$ chown -R www-data app/tmp

If for some reason CakePHP can’t write to that directory, you’ll see warnings and uncaught exceptions that cache data cannot be written.

Creating the Blog Database

Next, let’s set up the underlying database for our blog. If you haven’t already done so, create an empty database for use in this tutorial, with a name of your choice. Right now, we’ll just create a single table to store our posts. We’ll also throw in a few posts right now to use for testing purposes. Execute the following SQL statements into your database:

/* First, create our posts table: */
title VARCHAR(50),
body TEXT,
/* Then insert some posts for testing: */
INSERT INTO posts (title, body, created)
VALUES ('The title', 'This is the post body.', NOW());
INSERT INTO posts (title, body, created)
VALUES ('A title once again', 'And the post body follows.', NOW());
INSERT INTO posts (title, body, created)
VALUES ('Title strikes back', 'This is really exciting! Not.', NOW());

The choices on table and column names are not arbitrary. If you follow CakePHP’s database naming conventions, and CakePHP’s class naming conventions (both outlined in CakePHP Conventions), you’ll be able
to take advantage of a lot of free functionality and avoid configuration. CakePHP is flexible enough to accommodate even the worst legacy database schema, but adhering to convention will save you time.

Check out CakePHP Conventions for more information, but suffice it to say that naming our table ‘posts’ automatically hooks it to our Post model, and having fields called ‘modified’ and ‘created’ will be automagically managed by CakePHP.

CakePHP Database Configuration

Onward and upward: let’s tell CakePHP where our database is and how to connect to it. For many, this is the first and last time you configure anything.

A copy of CakePHP’s database configuration file is found in /app/Config/database.php.default. Make a copy of this file in the same directory, but name it database.php.

The config file should be pretty straightforward: just replace the values in the $default array with those that apply to your setup. A sample completed configuration array might look something like the following:

public $default = array(
'datasource' => 'Database/Mysql',
'persistent' => false,
'host' => 'localhost',
'port' => '',
'login' => 'cakeBlog',
'password' => 'c4k3-rUl3Z',
'database' => 'cake_blog_tutorial',
'schema' => '',
'prefix' => '',
'encoding' => 'utf8'

Once you’ve saved your new database.php file, you should be able to open your browser and see the CakePHP welcome page. It should also tell you that your database connection file was found, and that CakePHP can successfully connect to the database.

Note: Remember that you’ll need to have PDO, and pdo_mysql enabled in your php.ini.

Optional Configuration

There are a few other items that can be configured. Most developers complete these laundry-list items, but they’re not required for this tutorial. One is defining a custom string (or “salt”) for use in security hashes.
The second is defining a custom number (or “seed”) for use in encryption.

The security salt is used for generating hashes. Change the default Security.salt value in /app/Config/core.php. The replacement value should be long, hard to guess and be as random as you can make it:

* A random string used in security hashing methods.
Configure::write('Security.salt', 'pl345e-P45s_7h3*S@l7!');

The cipher seed is used for encrypt/decrypt strings. Change the default Security.cipherSeed value by editing /app/Config/core.php. The replacement value should be a large random integer:

* A random numeric string (digits only) used to encrypt/decrypt strings.
Configure::write('Security.cipherSeed', '7485712659625147843639846751');

A Note on mod_rewrite

Occasionally new users will run into mod_rewrite issues. For example if the CakePHP welcome page looks a little funny (no images or CSS styles), it probably means mod_rewrite is not functioning on your system. Please refer to one of the sections below about URL rewriting for your webserver to get you up and running:

URL Rewriting

Apache and mod_rewrite (and .htaccess)

While CakePHP is built to work with mod_rewrite out of the box–and usually does–we’ve noticed that a few users struggle with getting everything to play nicely on their systems.

Here are a few things you might try to get it running correctly. First look at your httpd.conf. (Make sure you are editing the system httpd.conf rather than a user- or site-specific httpd.conf.).

These files can vary between different distributions and Apache versions. You may also take a look at for further information.

  • Make sure that an .htaccess override is allowed and that AllowOverride is set to All for the correct DocumentRoot. You should see something similar to:

# Each directory to which Apache has access can be configured with
# to which services and features are allowed and/or disabled in that
# directory (and its subdirectories).
# First, we configure the "default" to be a very restrictive set of
# features.
<Directory />
Options FollowSymLinks
AllowOverride All
# Order deny,allow
# Deny from all

For users having apache 2.4 and above, you need to modify the configuration file for your httpd.conf or virtual host configuration to look like the following:

  • Make sure you are loading mod_rewrite correctly. You should see something like:

LoadModule rewrite_module libexec/apache2/

In many systems these will be commented out by default, so you may just need to remove the leading # symbols. After you make changes, restart Apache to make sure the settings are active.Verify that your .htaccess files are actually in the right directories. Some operating systems treat files
that start with ‘.’ as hidden and therefore won’t copy them.

  • Make sure your copy of CakePHP comes from the downloads section of the site or our Git repository, and has been unpacked correctly, by checking for .htaccess files.

CakePHP root directory (must be copied to your document; redirects everything to your CakePHP app):

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule ^$ app/webroot/ [L]
RewriteRule (.*) app/webroot/$1 [L]

CakePHP app directory (will be copied to the top directory of your application by bake):

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule ^$ webroot/ [L]
RewriteRule (.*) webroot/$1 [L]

CakePHP webroot directory (will be copied to your application’s web root by bake):

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php [QSA,L]

If your CakePHP site still has problems with mod_rewrite, you might want to try modifying settings for Virtual Hosts. On Ubuntu, edit the file /etc/apache2/sites-available/default (location is distributiondependent).
In this file, ensure that AllowOverride None is changed to AllowOverride
All, so you have:

<Directory />
Options FollowSymLinks
AllowOverride All
<Directory /var/www>
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Order Allow,Deny
Allow from all

On Mac OSX, another solution is to use the tool virtualhostx5 to make a Virtual Host to point to your folder.

For many hosting services (GoDaddy, 1and1), your web server is actually being served from a user directory that already uses mod_rewrite. If you are installing CakePHP into a user directory (, or any other URL structure that already utilizes mod_rewrite, you’ll need to add RewriteBase statements to the .htaccess files CakePHP uses (/.htaccess, /app/.htaccess, /app/webroot/.htaccess).

This can be added to the same section with the RewriteEngine directive, so for example, your webroot,htaccess file would look like:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /path/to/cake/app
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f

RewriteRule ^(.*)$ index.php [QSA,L]

The details of those changes will depend on your setup, and can include additional things that are not related to CakePHP. Please refer to Apache’s online documentation for more information.

  • (Optional) To improve production setup, you should prevent invalid assets from being parsed by CakePHP. Modify your webroot .htaccess to something like:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /path/to/cake/app
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !^/(app/webroot/)?(img|css|js)/(.*)$
RewriteRule ^(.*)$ index.php [QSA,L]

The above will simply prevent incorrect assets from being sent to index.php and instead display your webserver’s 404 page.

Additionally you can create a matching HTML 404 page, or use the default built-in CakePHP 404 by adding an ErrorDocument directive:

ErrorDocument 404 /404-not-found

Pretty URLs on nginx

nginx does not make use of .htaccess files like Apache, so it is necessary to create those rewritten URLs in the site-available configuration. Depending upon your setup, you will have to modify this, but at the very least, you will need PHP running as a FastCGI instance.

server {
listen 80;
rewrite ^(.*)$1 permanent;
server {
listen 80;
# root directive should be global
root /var/www/;
index index.php;
access_log /var/www/;
error_log /var/www/;
location / {try_files $uri $uri/ /index.php?$args;
location ~ \.php$ {
try_files $uri =404;
include /etc/nginx/fastcgi_params;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;

If for some exotic reason you cannot change your root directory and need to run your project from a subfolder like, you will have to inject “/webroot” in each request.

location ~ ^/(subfolder)/(.*)? {
index index.php;
set $new_uri /$1/webroot/$2;
try_files $new_uri $new_uri/ /$1/index.php?$args;
... php handling ...

Note: Recent configuration of PHP-FPM is set to listen to php-fpm socket instead of TCP port 9000 on address If you get 502 bad gateway error from above configuration, try replacing fastcgi_pass from TCP port to socket path (eg: fastcgi_pass unix:/var/run/php5-fpm.sock;).

Anil  Bist

Skills    Cakephp

Qualifications :- High School - SLV, College/University - Graphic Era Deemed Univ University,
Location :-Dehradun,Dehradun,Uttarakhand,India

I started my Professional Journey in 2006 with one of the Web Development Company in Bangalore and my 1st framework was "Ruby on Rail" as Web development and delivered around 5+ Projects using this platform. Then came another dimension as JEE/Sturst framework, Gradually I realized that I want to build something on my own and give my passion and energy on creating something different a


  Students (0)