Get Visitor Information by IP Address in PHP
How to get location from IP address using PHP
In this exercise, you will learn how to get a visitor's full information, like country, state, region, timezone, latitude, longitude and so on, using the visitor's IP address using PHP programming language.
There may be different purposes for getting the IP address of the visitor. We can easily track the visitor activity on the website and get information about the full geographical locations of the visitors. We can show or hide visitors from a specific country or region for security reasons. We can also store the visitor's information in the database to create our own analytics report.
PHP provides the simplest way to get the visitor's IP address. The $_SERVER superglobal variable is used to get all of the IP relevant information. The REMOTE_ADDR constant is used to pass as a parameter to $_SERVER for getting the IP address of the current user.
$ip = $_SERVER['REMOTE_ADDR'];
Next, we will use the third API to get the full information about the IP address. In this article, we are using the 'geoplugin' API. The information received by the third party is not more readable. So, first convert them into a string using PHP file_get_contents() function and then decode them using the json_decode() function.
$ip_info = @json_decode(file_get_contents("http://www.geoplugin.net/json.gp?ip=".$ip));
Complete Code: Get Visitor Information by IP Address in PHP
Here is a very simple code in PHP to get the IP address of the visitor and get full location information about the visitor-
Output of the above code -
Country Code = PS
City =
Region =
Latitude = 32
Longitude = 35.25
Timezone = Asia/Hebron
Continent Code = AS
Continent Name = Asia
Timezone = Asia/Hebron
Currency Code =