DEV Community

Cover image for How To Get Data From User IP
Karim Abdallah
Karim Abdallah

Posted on

How To Get Data From User IP

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: $userIP

replace $userIP with the real user ip such as

The Response should be like this photo:

api response

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:

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; }
Enter fullscreen mode Exit fullscreen mode

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().'"}';
Enter fullscreen mode Exit fullscreen mode

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)