CodeIgniter mobile OS detection

Download library from http://mobiledetect.net Put Mobile_Detect.php in to 'libraries'

inside main controller

public function index() {
    $this -> load -> library('Mobile_Detect');
    $detect = new Mobile_Detect();
    if ($detect->isMobile() || $detect->isTablet() || $detect->isAndroidOS()) {
        header("Location: ".$this->config->item('base_url')."/mobile"); exit;
    }
}

Find documentation on https://dwij.net/mobile-os-detection-in-php-codeigniter/


Load lib.

$this->load->library('user_agent');

use this function to detect is mobile

$mobile=$this->agent->is_mobile();
if($mobile){
  //your code
}

I borrowed/stole this method of loading the class from the phpexcel codeigniter integration.

Download library from http://mobiledetect.net, but put Mobile_Detect.php in 'third_party' then create MobileDetect.php in 'libraries' and put the following code in it:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
require_once APPPATH."third_party/Mobile_Detect.php";

class MobileDetect extends Mobile_Detect {
  public function __construct() {
    parent::__construct();
  }
}

Now you can use it in your controllers like this:

$this->load->library('MobileDetect');
if ($this->mobiledetect->isMobile()) {
    //do something cool;
}

I'm sure there are other (even better) ways to integrate mobiledetect into codeigniter, I just wanted to share the way I did it, I hope it's helpful.

A couple of notes:

1) You don't have to use the stub file MobileDetect.php, if you put Mobile_Detect.php directly in 'libraries' you can still use it without $detect = new Mobile_Detect(); instead call the functions liked this: $this->mobile_detect->isMobile()

2) The name of the stub file class can be anything you want as long as you follow CodeIgniter guidelines. So for example you could use 'MD' as the class name and then reference it with $this->md->isMobile()

3) I recommend adding if ( ! defined('BASEPATH')) exit('No direct script access allowed'); after the opening <?php of Mobile_Detect.php to prevent direct access to the class.