Hello, in this article we will learn how to get user data from it's IP address such as (User Country, Timezone, City, Region Name, Country Code, Continent Name, Currency and more).
Notice: Before we start you must know why we get data from userIP, Imagine you're working on a project and want to create ban system that block user or you want to get & save user country & language to display the right localization for that user for example if there is a user from United Stated opened your website you will get his country & language to make your website language is English and Currency is USD.
So These Information Are Very Important To Make Your Project Work Properly.
We will use a very simple Api called geoplugin that will provide us all mentioned info above.
you can easily call this url:
http://www.geoplugin.net/json.gp?ip= $userIP
replace $userIP with the real user ip such as 156.000.00.00
The Response should be like this photo:
Now you can easily get the response in JSON format and use it directly in your project, but if you want to customize the response such as get specified keys or change keys name You Will Use This Library From Github: github.com/kimoandroid/UserDataFromIp
I've Created This Library To Detect User IP Auto By Calling The Url With This Code:
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$this->userip = filter_var($_SERVER['HTTP_CLIENT_IP'], FILTER_VALIDATE_IP);
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$this->userip = filter_var($_SERVER['HTTP_X_FORWARDED_FOR'], FILTER_VALIDATE_IP);
} else if (!empty($_SERVER['REMOTE_ADDR'])) {
$this->userip = filter_var($_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP);
} else { $this->userip = NULL; }
This code might get wrong ip address or might get inaccurate user ip but you can use it if you can't get the ip from user device OR you can delete this code from the library files and get user ip from GET response, It's up to you.
Now i've customized this library to get Five keys only from the api and display the customized response in my own JSON format.
as you see here in get_data.php file it's a simple OOP with getters & setters so you can edit them easily:
finally at index.php file i called the Class to get user data from the api with this code:
// call get_data class
require "get_data.php";
$getData = new get_data();
// print user data in a simple json format.
echo '{"ip": "'.$getData->get_ip().'", "country": "'.$getData->get_country().'", "timezone": "'.$getData->get_timezone().'", "continent": "'.$getData->get_continent().'", "currency": "'.$getData->get_currency().'"}';
you can customize the response in advanced JSON Array but i used simple json to clarify only.
That's All For Today, Thanks For Reading & Follow For More :)
Top comments (0)