How to Get User IP Address in CodeIgniter

On 8/25/2015

Hi, this quick post discusses about getting user ip address in php codeigniter framework. Say you have an application built on code igniter mvc and you want to collect visitor’s ip address. The easiest solution is to use the codeigniter’s input class.

CodeIgniter input class serves two important purposes. 1. It ensures security by pre-processing the global input data and 2. It does provide helper functions to fetch the input data and pre-process it.


Unlike other codeigniter libraries, we don’t have to manually initialize this input class as it is done automatically by the system.

Get IP Address of the User in CodeIgniter

The input class provides two built-in functions namely ip_address() and valid_ip() to process the ip address.

To get the ip address of the current user use it like this,

$ip = $this->input->ip_address();

This returns the current user’s ip address. It returns if the ip is not valid.

Validate IP Address

With the help of the function valid_id($ip) you can validate any ip address. It takes up the ip address as parameter and returns TRUE if it is valid or FALSE if not valid.

You can check for valid ip like this,

echo ($this->input->valid_ip($ip)?'Valid':'Not Valid');

It also takes up an optional second parameter, a string value of ‘IPv4’ or ‘IPv6’ to specify an IP format. If it is not provided it will check for both formats by default.

That was all about getting the client/user ip address in codeigniter.


No comments:

Post a Comment

Contact Form


Email *

Message *