Home » Php » ip address – Country name from php

ip address – Country name from php

Posted by: admin July 12, 2020 Leave a comment

Questions:

How to get country name from an Ip address using Php with out using a commercial GeoIP Region Edition. Please does any one help me?

How to&Answers:

I don’t think you can do it simply using PHP, but I have found a free API solution that you can use. It requires simple post and response.
http://www.hostip.info/use.html

example post:
http://api.hostip.info/get_html.php?ip=12.215.42.19

example response:
Country: UNITED STATES (US)
City: Sugar Grove, IL

Answer:

Code

$json = file_get_contents('http://freegeoip.appspot.com/json/66.102.13.106');
$expression = json_decode($json);
print_r($expression);

Result

stdClass Object
(
    [status] => 1
    [ip] => 66.102.13.106
    [countrycode] => US
    [countryname] => United States
    [regioncode] => CA
    [regionname] => California
    [city] => Mountain View
    [zipcode] => 94043
    [latitude] => 37.4192
    [longitude] => -122.057
)

To get countryname

echo $expression->countryname;

Result

United States

Answer:

Use the free IP geolocation webservice

Answer:

GeoIP PHP API

Answer:

If you want to setup your own app here is the git source of the above solution, by Peter (I always prefer self hosted solution instead of hitting and relying on some other service):

FreeGeoIP Source Code

Answer:

Use apinotes external geolocation api

Example:

http://apinotes.com/ipaddress/ip.php?ip=27.62.184.235

URL:  http://apinotes.com/ipaddress/ip.php
Parameter Name: ip
Value:  27.62.184.23 (ipv4 address)

Example For Get Country Details By Ip Address In Php

<?php
$ip = '27.62.184.235';
$json_data = file_get_contents("http://apinotes.com/ipaddress/ip.php?ip=$ip");
$ip_data = json_decode($json_data, TRUE);
if ($ip_data['status'] == 'success') {
    ?>
    <p>Ip Address: <?php echo $ip_data['ip'] ?></p>
    <p>Country Name: <?php echo $ip_data['country_name'] ?></p>
    <p>Country Code: <?php echo $ip_data['country_code'] ?></p>
    <p>Country Code (3 digit): <?php echo $ip_data['country_code3'] ?></p>
    <p>Region Code: <?php echo $ip_data['region_code'] ?></p>
    <p>Region Name: <?php echo $ip_data['region_name'] ?></p>
    <p>City Name: <?php echo $ip_data['city_name'] ?></p>
    <p>Latitude: <?php echo $ip_data['latitude'] ?></p>
    <p>Longitude: <?php echo $ip_data['longitude'] ?></p>
<?php }
?>