Installation

CakePHP has a few system requirements:

  • HTTP Server. For example: Apache. Having mod_rewrite is preferred, butby no means required. You can also use nginx, or Microsoft IIS if you prefer
  • PHP 7.2.0 or greater
  • mbstring PHP extension
  • intl PHP extension
  • simplexml PHP extension
  • PDO PHP extension

Note

In XAMPP, intl extension is included but you have to uncommentextension=php_intl.dll in php.ini and restart the server throughthe XAMPP Control Panel.

In WAMP, the intl extension is “activated” by default but not working.To make it work you have to go to php folder (by default)C:\wamp\bin\php\php{version}, copy all the files that looks likeicu*.dll and paste them into the apache bin directoryC:\wamp\bin\apache\apache{version}\bin. Then restart all servicesand it should be OK.

While a database engine isn’t required, we imagine that most applications willutilize one. CakePHP supports a variety of database storage engines:

  • MySQL (5.5.3 or greater)
  • MariaDB (5.5 or greater)
  • PostgreSQL
  • Microsoft SQL Server (2008 or higher)
  • SQLite 3

Note

All built-in drivers require PDO. You should make sure you have the correctPDO extensions installed.

Installing CakePHP

Before starting you should make sure that your PHP version is up to date:

  1. php -v

You should have PHP 7.2.0 (CLI) or higher.Your webserver’s PHP version must also be of 7.2.0 or higher, and should bethe same version your command line interface (CLI) uses.

Installing Composer

CakePHP uses Composer, a dependency management tool,as the officially supported method for installation.

  • Installing Composer on Linux and macOS

    • Run the installer script as described in theofficial Composer documentationand follow the instructions to install Composer.

    • Execute the following command to move the composer.phar to a directorythat is in your path:

  1. mv composer.phar /usr/local/bin/composer
  • Installing Composer on Windows

For Windows systems, you can download Composer’s Windows installerhere. Furtherinstructions for Composer’s Windows installer can be found within theREADME here.

Create a CakePHP Project

You can create a new CakePHP application using composer’s create-projectcommand:

  1. composer create-project --prefer-dist cakephp/app my_app_name

Once Composer finishes downloading the application skeleton and the core CakePHPlibrary, you should have a functioning CakePHP application installed viaComposer. Be sure to keep the composer.json and composer.lock files with therest of your source code.

You can now visit the path to where you installed your CakePHP application andsee the default home page. To change the content of this page, edittemplates/Pages/home.php.

Although composer is the recommended installation method, there arepre-installed downloads available onGithub.Those downloads contain the app skeleton with all vendor packages installed.Also it includes the composer.phar so you have everything you need forfurther use.

Keeping Up To Date with the Latest CakePHP Changes

By default this is what your application composer.json looks like:

  1. "require": {
  2. "cakephp/cakephp": "4.0.*"
  3. }

Each time you run php composer.phar update you will receive patchreleases for this minor version. You can instead change this to ^4.0 toalso receive the latest stable minor releases of the 4.x branch.

Installation using Oven

Another quick way to install CakePHP is via Oven.It is a small PHP script which checks the necessary system requirements,and creates a new CakePHP application.

Note

IMPORTANT: This is not a deployment script. It is aimed to help developersinstall CakePHP for the first time and set up a development environmentquickly. Production environments should consider several other factors, likefile permissions, virtualhost configuration, etc.

Permissions

CakePHP uses the tmp directory for a number of different operations.Model descriptions, cached views, and session information are a fewexamples. The logs directory is used to write log files by the defaultFileLog engine.

As such, make sure the directories logs, tmp and all its subdirectoriesin your CakePHP installation are writable by the web server user. Composer’sinstallation process makes tmp and its subfolders globally writeable to getthings up and running quickly but you can update the permissions for bettersecurity and keep them writable only for the web server user.

One common issue is that logs and tmp directories and subdirectoriesmust be writable both by the web server and the command line user. On a UNIXsystem, if your web server user is different from your command line user, youcan run the following commands from your application directory just once in yourproject to ensure that permissions will be setup properly:

  1. HTTPDUSER=`ps aux | grep -E '[a]pache|[h]ttpd|[_]www|[w]ww-data|[n]ginx' | grep -v root | head -1 | cut -d\ -f1`
  2. setfacl -R -m u:${HTTPDUSER}:rwx tmp
  3. setfacl -R -d -m u:${HTTPDUSER}:rwx tmp
  4. setfacl -R -m u:${HTTPDUSER}:rwx logs
  5. setfacl -R -d -m u:${HTTPDUSER}:rwx logs

In order to use the CakePHP console tools, you need to ensure thatbin/cake file is executable. On *nix or macOS, you canexecute:

  1. chmod +x bin/cake

On Windows, the .bat file should be executable already. If you are usinga Vagrant, or any other virtualized environment, any shared directories need tobe shared with execute permissions (Please refer to your virtualizedenvironment’s documentation on how to do this).

If, for whatever reason, you cannot change the permissions of the bin/cakefile, you can run the CakePHP console with:

  1. php bin/cake.php

Development Server

A development installation is the fastest way to setup CakePHP. In thisexample, we use CakePHP’s console to run PHP’s built-in web server whichwill make your application available at http://host:port. From the appdirectory, execute:

  1. bin/cake server

By default, without any arguments provided, this will serve your application athttp://localhost:8765/.

If there is conflict with localhost or port 8765, you can tellthe CakePHP console to run the web server on a specific host and/or portutilizing the following arguments:

  1. bin/cake server -H 192.168.13.37 -p 5673

This will serve your application at http://192.168.13.37:5673/.

That’s it! Your CakePHP application is up and running without having toconfigure a web server.

Note

Try bin/cake server -H 0.0.0.0 if the server is unreachable from other hosts.

Warning

The development server should never be used in a production environment.It is only intended as a basic development server.

If you’d prefer to use a real web server, you should be able to move your CakePHPinstall (including the hidden files) inside your web server’s document root. Youshould then be able to point your web-browser at the directory you moved thefiles into and see your application in action.

Production

A production installation is a more flexible way to setup CakePHP. Using thismethod allows an entire domain to act as a single CakePHP application. Thisexample will help you install CakePHP anywhere on your filesystem and make itavailable at http://www.example.com. Note that this installation may require therights to change the DocumentRoot on Apache webservers.

After installing your application using one of the methods above into thedirectory of your choosing - we’ll assume you chose /cake_install - yourproduction setup will look like this on the file system:

  1. /cake_install/
  2. bin/
  3. config/
  4. logs/
  5. plugins/
  6. resources/
  7. src/
  8. templates/
  9. tests/
  10. tmp/
  11. vendor/
  12. webroot/ (this directory is set as DocumentRoot)
  13. .gitignore
  14. .htaccess
  15. .travis.yml
  16. composer.json
  17. index.php
  18. phpunit.xml.dist
  19. README.md

Developers using Apache should set the DocumentRoot directive for the domainto:

  1. DocumentRoot /cake_install/webroot

If your web server is configured correctly, you should now find your CakePHPapplication accessible at http://www.example.com.

Fire It Up

Alright, let’s see CakePHP in action. Depending on which setup you used, youshould point your browser to http://example.com/ or http://localhost:8765/. Atthis point, you’ll be presented with CakePHP’s default home, and a message thattells you the status of your current database connection.

Congratulations! You are ready to create your first CakePHP application.

URL Rewriting

Apache

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

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

These files can vary between different distributions and Apache versions. Youmay also take a look at http://wiki.apache.org/httpd/DistrosDefaultLayout forfurther information.

  • Make sure that an .htaccess override is allowed and that AllowOverride is setto All for the correct DocumentRoot. You should see something similar to:
  1. # Each directory to which Apache has access can be configured with respect
  2. # to which services and features are allowed and/or disabled in that
  3. # directory (and its subdirectories).
  4. #
  5. # First, we configure the "default" to be a very restrictive set of
  6. # features.
  7. <Directory />
  8. Options FollowSymLinks
  9. AllowOverride All
  10. # Order deny,allow
  11. # Deny from all
  12. </Directory>
  • Make sure you are loading mod_rewrite correctly. You should see somethinglike:
  1. LoadModule rewrite_module libexec/apache2/mod_rewrite.so

In many systems these will be commented out by default, so you may just needto 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. Someoperating systems treat files that start with ‘.’ as hidden and thereforewon’t copy them.

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

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

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

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

  1. <IfModule mod_rewrite.c>
  2. RewriteEngine On
  3. RewriteCond %{REQUEST_FILENAME} !-f
  4. RewriteRule ^ index.php [L]
  5. </IfModule>

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

  1. <Directory />
  2. Options FollowSymLinks
  3. AllowOverride All
  4. </Directory>
  5. <Directory /var/www>
  6. Options FollowSymLinks
  7. AllowOverride All
  8. Order Allow,Deny
  9. Allow from all
  10. </Directory>

On macOS, another solution is to use the toolvirtualhostx to make a VirtualHost to point to your folder.

For many hosting services (GoDaddy, 1and1), your web server is beingserved from a user directory that already uses mod_rewrite. If you areinstalling CakePHP into a user directory(http://example.com/~username/cakephp/), or any other URL structure thatalready utilizes mod_rewrite, you’ll need to add RewriteBase statements tothe .htaccess files CakePHP uses (.htaccess, webroot/.htaccess).

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

  1. <IfModule mod_rewrite.c>
  2. RewriteEngine On
  3. RewriteBase /path/to/app
  4. RewriteCond %{REQUEST_FILENAME} !-f
  5. RewriteRule ^ index.php [L]
  6. </IfModule>

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

  • (Optional) To improve production setup, you should prevent invalid assetsfrom being parsed by CakePHP. Modify your webroot .htaccess to somethinglike:
  1. <IfModule mod_rewrite.c>
  2. RewriteEngine On
  3. RewriteBase /path/to/app/
  4. RewriteCond %{REQUEST_FILENAME} !-f
  5. RewriteCond %{REQUEST_URI} !^/(webroot/)?(img|css|js)/(.*)$
  6. RewriteRule ^ index.php [L]
  7. </IfModule>

The above will prevent incorrect assets from being sent to index.phpand instead display your web server’s 404 page.

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

  1. ErrorDocument 404 /404-not-found

nginx

nginx does not make use of .htaccess files like Apache, so it is necessary tocreate those rewritten URLs in the site-available configuration. This is usuallyfound in /etc/nginx/sites-available/your_virtual_host_conf_file. Dependingon your setup, you will have to modify this, but at the very least, you willneed PHP running as a FastCGI instance.The following configuration redirects the request to webroot/index.php:

  1. location / {
  2. try_files $uri $uri/ /index.php?$args;
  3. }

A sample of the server directive is as follows:

  1. server {
  2. listen 80;
  3. listen [::]:80;
  4. server_name www.example.com;
  5. return 301 http://example.com$request_uri;
  6. }
  7.  
  8. server {
  9. listen 80;
  10. listen [::]:80;
  11. server_name example.com;
  12.  
  13. root /var/www/example.com/public/webroot;
  14. index index.php;
  15.  
  16. access_log /var/www/example.com/log/access.log;
  17. error_log /var/www/example.com/log/error.log;
  18.  
  19. location / {
  20. try_files $uri $uri/ /index.php?$args;
  21. }
  22.  
  23. location ~ \.php$ {
  24. try_files $uri =404;
  25. include fastcgi_params;
  26. fastcgi_pass 127.0.0.1:9000;
  27. fastcgi_index index.php;
  28. fastcgi_intercept_errors on;
  29. fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
  30. }
  31. }

Note

Recent configurations of PHP-FPM are set to listen to the unix php-fpmsocket instead of TCP port 9000 on address 127.0.0.1. If you get 502 badgateway errors from the above configuration, try update fastcgi_pass touse the unix socket path (eg: fastcgi_passunix:/var/run/php/php7.1-fpm.sock;) instead of the TCP port.

IIS7 (Windows hosts)

IIS7 does not natively support .htaccess files. While there areadd-ons that can add this support, you can also import htaccessrules into IIS to use CakePHP’s native rewrites. To do this, followthese steps:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <configuration>
  3. <system.webServer>
  4. <rewrite>
  5. <rules>
  6. <rule name="Exclude direct access to webroot/*"
  7. stopProcessing="true">
  8. <match url="^webroot/(.*)$" ignoreCase="false" />
  9. <action type="None" />
  10. </rule>
  11. <rule name="Rewrite routed access to assets(img, css, files, js, favicon)"
  12. stopProcessing="true">
  13. <match url="^(font|img|css|files|js|favicon.ico)(.*)$" />
  14. <action type="Rewrite" url="webroot/{R:1}{R:2}"
  15. appendQueryString="false" />
  16. </rule>
  17. <rule name="Rewrite requested file/folder to index.php"
  18. stopProcessing="true">
  19. <match url="^(.*)$" ignoreCase="false" />
  20. <action type="Rewrite" url="index.php"
  21. appendQueryString="true" />
  22. </rule>
  23. </rules>
  24. </rewrite>
  25. </system.webServer>
  26. </configuration>

Once the web.config file is created with the correct IIS-friendly rewrite rules,CakePHP’s links, CSS, JavaScript, and rerouting should work correctly.

I Can’t Use URL Rewriting

If you don’t want or can’t get mod_rewrite (or some other compatible module)running on your server, you will need to use CakePHP’s built in pretty URLs.In config/app.php, uncomment the line that looks like:

  1. 'App' => [
  2. // ...
  3. // 'baseUrl' => env('SCRIPT_NAME'),
  4. ]

Also remove these .htaccess files:

  1. /.htaccess
  2. webroot/.htaccess

This will make your URLs look likewww.example.com/index.php/controllername/actionname/param rather thanwww.example.com/controllername/actionname/param.