Tuesday, July 03, 2012

Browser Detection with Codeigniter

Like most other classes in CodeIgniter, the User Agent class is initialized in your controller using the $this -> load -> library function:
$this -> load -> library('user_agent');
Or 

You can auto-load it by editing the autoload.php file. You can find the file in the application/config/autoload.php file. Just find the $autoload array and add 'user_agent' like below
$autoload['libraries'] = array('user_agent');

Now in the Controller file I have named it useragent.php file edit as follow:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');


class Useragent extends CI_Controller 
{
public function index()
{
$this -> load -> view('user_agent');
}
}


Now in the view file I have named it user_agent.php file edit as follow:
</span><span style="background-color: white; ">User Agent Information</span><span style="background-color: white; ">


<html>
<head>
<title>User Agent Information</title>
<head>


<body>
<?php
        if ($this -> agent -> is_browser()) {
        $agent = $this -> agent -> browser().' '.$this -> agent -> version(); }
        elseif ($this -> agent -> is_robot()) {
        $agent = $this -> agent -> robot(); }
        elseif ($this -> agent -> is_mobile()) {
        $agent = $this -> agent -> mobile(); } 
        else { $agent = 'Unidentified User Agent'; }
        ?>


<?php echo $agent; ?> <br />
<?php echo $this -> agent -> platform(); ?> <br />
<?php echo $this -> agent -> is_referral();?> <br />
<?php echo $this -> agent -> browser();?> <br />
<?php echo $this -> agent -> version();?> <br />
<?php if($this -> agent -> is_referral()) echo $this -> agent -> referrer();?> <br />
<?php echo $this -> agent -> agent_string(); ?> <br />
<?php if($this -> agent -> accept_lang('en')) echo 'English'; ?> <br />
<?php if($this -> agent -> accept_charset('utf-8')) echo 'utf-8'; ?>
</body>




Output: I have executed this code in my localhost it output
Chrome 20.0.1132.47 

Windows 7 



Chrome 

20.0.1132.47 



Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.47 Safari/536.11 

English 

utf-8


1 comment:

  1. i was looking for hire codeigniter programmers and find your post and i must say this is quite useful for me thanks for sharing.

    ReplyDelete