How to get ip details without third party API using PHP

02 November 2018, in Web development
Share on Social Media: Share on facebook Share on twitter Share on google

Simple PHP script to get vistor or customer ip details without using any third party API and these details are important for marketing analysis. So we are going implement to get visitor ip details without using any third party API. The details which are

  1. Country
  2. City
  3. Region
  4. Latitude
  5. Longitude and more.

It helps you to segment the users based on country or city or region. For the implementation we are using slim framework and PHP geoip. we are using maxmind standalone php composer package Here is sample route code

$app->get('/', function(Request $request, Response $response, array $args){
	$ip = get_ip_address();
	if(empty($ip) === true){
		return $response->withJson([
			'error' => [
				'ip' => 'IP cannot be empty'
			]
		]);
	}

	if(!filter_var($ip, FILTER_VALIDATE_IP)) {
	   return $response->withJson([
			'error' => [
				'ip' => 'Not a valid IP address'
			]
		]);
	}

	$gi = geoip_open(DATA_PATH, GEOIP_STANDARD);
	$record = GeoIP_record_by_addr($gi, $ip);
	$record->ip = $ip;

	return $response->withJson($record);
});

Method get_ip_address() is used to get visitor IP

function get_ip_address() {
    // check for shared internet/ISP IP
    if (!empty($_SERVER['HTTP_CLIENT_IP']) && validate_ip($_SERVER['HTTP_CLIENT_IP'])) {
        return $_SERVER['HTTP_CLIENT_IP'];
    }

    // check for IPs passing through proxies
    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        // check if multiple ips exist in var
        if (strpos($_SERVER['HTTP_X_FORWARDED_FOR'], ',') !== false) {
            $iplist = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            foreach ($iplist as $ip) {
                if (validate_ip($ip))
                    return $ip;
            }
        } else {
            if (validate_ip($_SERVER['HTTP_X_FORWARDED_FOR']))
                return $_SERVER['HTTP_X_FORWARDED_FOR'];
        }
    }
    if (!empty($_SERVER['HTTP_X_FORWARDED']) && validate_ip($_SERVER['HTTP_X_FORWARDED']))
        return $_SERVER['HTTP_X_FORWARDED'];
    if (!empty($_SERVER['HTTP_X_CLUSTER_CLIENT_IP']) && validate_ip($_SERVER['HTTP_X_CLUSTER_CLIENT_IP']))
        return $_SERVER['HTTP_X_CLUSTER_CLIENT_IP'];
    if (!empty($_SERVER['HTTP_FORWARDED_FOR']) && validate_ip($_SERVER['HTTP_FORWARDED_FOR']))
        return $_SERVER['HTTP_FORWARDED_FOR'];
    if (!empty($_SERVER['HTTP_FORWARDED']) && validate_ip($_SERVER['HTTP_FORWARDED']))
        return $_SERVER['HTTP_FORWARDED'];

    // return unreliable ip since all else failed
    return $_SERVER['REMOTE_ADDR'];
}


function validate_ip($ip)
{
 if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false) {
 return false;
 }
 return true;
}


For working demo you can download from following link Download




Comments