Configure CakePHP 2.x to Detect and Serve Mobile Browser Pages

Written by James McDonald

September 26, 2012

Put here for later:

Only thing needing to be added would be a cookie based ‘request desktop site’ option…


  • The above posts are for older versions of Cakephp which had a VIEW constant
  • assumed that the view directory would be lowercase

The following is a copy and paste of my app/Controllers/AppController.php class.

class AppController extends Controller {

	public $components = array('RequestHandler');

	public function beforeFilter(){
 	  if ($this->RequestHandler->isMobile()) {

            // required for CakePHP 2.2.2
            $viewDir = App::path('View'); 
            // returns an array
             * array(
             * 		(int) 0 => '/var/www/maps-cakephp2/app/View/'
             * ) 

            $mobileViewFile = $viewDir[0] . $this->viewPath 
                              . '/mobile/' . 
                              $this->params['action'] . '.ctp';

            // use this to log the output to
            // app/tmp/logs/debug.log

            if (file_exists($mobileViewFile)) {
               // if device is mobile, change layout to mobile
               // but only if a view exists for it.
                $this->layout = 'mobile';
               // and if a mobile view file has been 
               // created for the action, serve it instead 
                // of the default view file

                $mobileView = $this->viewPath . '/mobile/';
                $this->viewPath = $mobileView;




  1. Benny L.E.P

    great solution, working in cakephp 2.3.1
    thank you 🙂

  2. kicaj

    There is static method for detect?


Submit a Comment

Your email address will not be published.

You May Also Like…

PHP Iterators

Just came across a Youtube talk "Iterators in PHP" by Jake Smith published in 2014 that steps through the many...

PHP array_map Multiple Arrays

array_map can take multiple arrays. I like how it starts mapping through them starting at the first element of each...