Search code examples
codeigniteruser-agent

Codeigniter user_agent


This is my first time developing a responsive website, and I attempted using the CodeIgniter user_agent class.

I notice that there's

is_mobile()

and

is_browser()

However, the picture I have in mind is for the website on a tablet to look pretty similar to the browser, and only the mobile site to load a different view file altogether.

However, is_mobile() includes both tablets and mobile phones, and it's not what I'm hoping for. Is there an alternative to this?

Reason: I am using jQuery mobile, and I load a completely different layout for the mobile phone, and I don't want this view to appear on tablets.


Solution

  • You have a couple of options.

    You can extend the library and create a method to check for tablet:

    class MY_User_agent extends CI_User_agent {
    
        public function __construct()
        {
            parent::__construct();
        }
    
        public function is_tablet()
        {
            //logic to check for tablet
        }
    }
    
    // usage
    $this->load->library('user_agent');
    $this->user_agent->is_tablet();
    

    Or you could override the existing is_mobile() method in the library to have the functionality you want:

    class MY_User_agent extends CI_User_agent {
    
        public function __construct()
        {
            parent::__construct();
        }
    
        public function is_mobile()
        {
            // you can copy the original method here and modify it to your needs
        }
    }
    
    // usage
    $this->load->library('user_agent');
    $this->user_agent->is_mobile();
    

    https://www.codeigniter.com/user_guide/general/creating_libraries.html


    Example

    application/libraries/MY_User_agent.php:

    class MY_User_agent extends CI_User_agent {
    
        public function __construct()
        {
            parent::__construct();
        }
    
        public function is_ipad()
        {
            return (bool) strpos($_SERVER['HTTP_USER_AGENT'],'iPad');
                // can add other checks for other tablets
        }
    }
    

    controller:

    public function index()
    {
        $this->load->library('user_agent');
    
        ($this->agent->is_ipad() === TRUE) ? $is_ipad = "Yes" : $is_ipad = "No";
    
        echo "Using ipad: $is_ipad";
    
    }