Get the user IP address using PHP
 22 September 2017
 Php
 Rodrigo Costa Corrêa

We often need to get what IP of the user accessing the site to determine some modifications or even redirects on the site. Through the IP it is possible to discover, for example, the city of the user (See Here) and with that personalize the site for the user.

To get the user's IP, just call the function below anywhere in your code.

PHP function used to discover the IP of the user of your site:

public static function getClientIp() {
		$ipaddress = '';
		if (isset ( $_SERVER ['HTTP_CLIENT_IP'] ))
			$ipaddress = $_SERVER ['HTTP_CLIENT_IP'];
		else if (isset ( $_SERVER ['HTTP_X_FORWARDED_FOR'] ))
			$ipaddress = $_SERVER ['HTTP_X_FORWARDED_FOR'];
		else if (isset ( $_SERVER ['HTTP_X_FORWARDED'] ))
			$ipaddress = $_SERVER ['HTTP_X_FORWARDED'];
		else if (isset ( $_SERVER ['HTTP_FORWARDED_FOR'] ))
			$ipaddress = $_SERVER ['HTTP_FORWARDED_FOR'];
		else if (isset ( $_SERVER ['HTTP_FORWARDED'] ))
			$ipaddress = $_SERVER ['HTTP_FORWARDED'];
		else if (isset ( $_SERVER ['REMOTE_ADDR'] ))
			$ipaddress = $_SERVER ['REMOTE_ADDR'];
		else
			$ipaddress = 'UNKNOWN';
		return $ipaddress;
	}