How to get User Country, State from IP in PHP

How to get User Country, State from IP in PHP

To Get Visitor Details like Country, State, City first we need to get visitor IP Address.

Step 1:

This function obtain the IP address of the visitor.

<?php
         function get_visitor_ip(){
		$ipaddress = '';
		if (getenv('HTTP_CLIENT_IP'))
			$ipaddress = getenv('HTTP_CLIENT_IP');
		else if(getenv('HTTP_X_FORWARDED_FOR'))
			$ipaddress = getenv('HTTP_X_FORWARDED_FOR');
		else if(getenv('HTTP_X_FORWARDED'))
			$ipaddress = getenv('HTTP_X_FORWARDED');
		else if(getenv('HTTP_FORWARDED_FOR'))
			$ipaddress = getenv('HTTP_FORWARDED_FOR');
		else if(getenv('HTTP_FORWARDED'))
			$ipaddress = getenv('HTTP_FORWARDED');
		else if(getenv('REMOTE_ADDR'))
			$ipaddress = getenv('REMOTE_ADDR');
		else
			$ipaddress = 'UNKNOWN';
		
		return $ipaddress;
	}
        $ipaddress= get_visitor_ip(); // Store the IP address

Step 2:

Use API to get Visitor IP Details. Here the geoPlugin API to get the IP details. This API return a JSON response. Use file_get_contents function to call API.

<?php
     $response = file_get_contents('http://www.geoplugin.net/json.gp?   ip='.$ipaddress);
     $data =  @json_decode($response);
     $country = $data->geoplugin_countryName;
     $state = $data->geoplugin_region;
     $latitude = $data->geoplugin_latitude; 
     $longitude = $data->geoplugin_longitude; 
     $currency_symbol =  $data->geoplugin_currencySymbol; 

Output:

Country Name:    United States
State Name:       Alaska
Latitude:        45.8491
Longitude:       -119.7143
Currency Symbol: $

Leave a Reply

Your email address will not be published. Required fields are marked *