Get Visitor’s Country and City from IP Address in PHP

In this tutorial, we will use php to get vistor’s country and city by ip address, this way is based on ipstack API.

1.Get verstor’s ip address using php

<?php
$ip = $_SERVER['REMOTE_ADDR'];
?>

2.Use ip address to get country and city

We will use ipstack api to get these information.

ipstak api likes:

http://api.ipstack.com/IP_ADDRESS?access_key=API_KEY

where API_KEY is your access key.

Then we will get country and city by this api in php.

<?php
$ip = $_SERVER['REMOTE_ADDR']; 
$api_key = "YOUR_API_KEY";
$freegeoipjson = file_get_contents("http://api.ipstack.com/".$ip."?access_key=".$api_key."");

$jsondata = json_decode($freegeoipjson);

$countryfromip = $jsondata->country_name;
$cityfromip = $jsondata->city;

echo "City: ". $cityfromip ."";
echo "<br/>";
echo "Country: ". $countryfromip ."";
?>
Posted Under