WP-Mix

A fresh mix of code snippets and tutorials

PHP Get Actual IP Address

Here are a couple of quick snippets to get the visitor’s actual IP address via PHP.

Method 1

This is the method that I use in my projects to get the actual IP address:

// get real ip address
function shapeSpace_get_real_ip() {
	
	$ip = 'undefined';
	
	if (isset($_SERVER)) {
		
		$ip = $_SERVER['REMOTE_ADDR'];
		
		if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
			
			$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
			
		} elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
			
			$ip = $_SERVER['HTTP_CLIENT_IP'];
		}
		
	} else {
		
		$ip = getenv('REMOTE_ADDR');
		
		if (getenv('HTTP_X_FORWARDED_FOR')) {
			
			$ip = getenv('HTTP_X_FORWARDED_FOR');
			
		} elseif (getenv('HTTP_CLIENT_IP')) {
			
			$ip = getenv('HTTP_CLIENT_IP');
		}
	}
	
	$ip = htmlspecialchars($ip, ENT_QUOTES, 'UTF-8');
	return $ip;
}

This is a plug-n-play snippet with no modification necessary. Just include in your script and call/use $address as needed. Covers just about every possible IP-address scenario.

Update! Here is a minimized version of the previous get-IP function:

function shapeSpace_get_real_ip() {
	$ip = 'undefined';
	if (isset($_SERVER)) {
		$ip = $_SERVER['REMOTE_ADDR'];
		if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
		elseif (isset($_SERVER['HTTP_CLIENT_IP'])) $ip = $_SERVER['HTTP_CLIENT_IP'];
	} else {
		$ip = getenv('REMOTE_ADDR');
		if (getenv('HTTP_X_FORWARDED_FOR')) $ip = getenv('HTTP_X_FORWARDED_FOR');
		elseif (getenv('HTTP_CLIENT_IP')) $ip = getenv('HTTP_CLIENT_IP');
	}
	$ip = htmlspecialchars($ip, ENT_QUOTES, 'UTF-8');
	return $ip;
}

That’s a bit nicer for copy/paste and quick-use scenarios.

Method 2

Here is another snippet found lurking in the archives. It’s a bit more comprehensive in that it returns not just a single IP address, but an entire array of all possible IP addresses. Great for serious IP analysis..

$ips = array();
$vars = array(
	'REMOTE_ADDR',
	'HTTP_X_FORWARDED',
	'HTTP_X_FORWARDED_FOR',
	'HTTP_FORWARDED',
	'HTTP_FORWARDED_FOR'
);
foreach ($vars as $key) {
	if (!empty($_SERVER[$key])) {
		$ips[] = $_SERVER[$key];
	}
}
$ips = array_unique($ips);
$ips = array_map('trim', $ips);
$ips = array_map('strip_tags', $ips);
$ips = array_map('htmlentities', $ips);

return $ips;

Again, this snippet is plug-n-play with no modification required. Just plop it in and call the $ip array as needed. The future is yours!

★ Pro Tip:

USP Pro