Codeigniter offers many ways to get user IP addresses; In this tutorial, you will learn how to get user IP addresses in CodeIgniter 4, and 3 applications.
How to get IP address in Codeigniter
You can use the following ways:
- Method 1: Using the $_SERVER Variable
- Method 2: Using the CodeIgniter Input Class
- Method 3: Using the CodeIgniter User Agent Class
Method 1: Using the $_SERVER Variable
The easiest way to get the IP address in CodeIgniter is by using the $_SERVER variable. The $_SERVER variable is a PHP superglobal that contains information about the server and the current request. To retrieve the IP address of the user, you can use the following code:
$ip_address = $_SERVER['REMOTE_ADDR'];
This code retrieves the user’s IP address and stores it in the $ip_address variable.
Method 2: Using the CodeIgniter Input Class
CodeIgniter provides an Input class that simplifies retrieving input data, including the IP address. To use this class, you need to load it in your controller or model by using the following code:
$this->load->library('input');
Once the library is loaded, you can retrieve the IP address of the user by using the following code:
$ip_address = $this->input->ip_address();
This code retrieves the user’s IP address and stores it in the $ip_address variable.
Method 3: Using the CodeIgniter User Agent Class
CodeIgniter also provides a User Agent class that allows you to retrieve information about the user’s browser and operating system. This class also provides a method to retrieve the IP address of the user. To use this class, you need to load it in your controller or model by using the following code:
$this->load->library('user_agent');
Once the library is loaded, you can retrieve the IP address of the user by using the following code:
$ip_address = $this->input->ip_address();
This code retrieves the user’s IP address and stores it in the $ip_address variable.
Conclusion
In this article, you have learned different ways to get the IP address in CodeIgniter.