Get IP Address and User Agent using CodeIgniter

you can easily collect visitor’s IP address or browser infirmation using Codeigniter “user_agent” library.

The User Agent Class provides functions that help identify information about the browser, mobile device, or robot visiting your site. In addition you can get referrer information as well as language and supported character-set information.

The user agent name definitions are located in a config file located at: application/config/user_agents.php.

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');

Example:

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

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';
}

echo $agent;

echo $this->agent->platform(); // Platform info (Windows, Linux, Mac, etc.)

if ($this->agent->is_browser('Safari'))
{
    echo 'You are using Safari.';
}
else if ($this->agent->is_browser())
{
    echo 'You are using a browser.';
}

Leave a Reply

Your email address will not be published. Required fields are marked *