Get location from an IP address in PHP

Today we’ll show you how to get location from an IP address in PHP. In this article, we will use the third party free API to get the geolocation (like country, state, city, latitude, longitude, timezone, currency, etc.) based on the IP address.

Check out the more articles in PHP.

Way to get location from an IP address

  1. Using geoPlugin API
  2. Using ipinfo API

1. Using geoPlugin API

Here we will use the following geoPlugin third party API to get the geo information.

Let’s use the above API with a static IP address to implement in a PHP file. After the API call, we need to use the file_get_contents() function to get the requested IP data in the JSON format. Then we will convert the JSON data to an array using the json_decode() function.

This is a free API and we can use it as below.

You will get the following output in the browser.

Get location information using geoPlugin API - Clue Mediator
Get location information using geoPlugin API – Clue Mediator

Also you can process it with a PHP cURL request.

The below output that you can see in the browser.

Get location information using CURL request - Clue Mediator
Get location information using CURL request – Clue Mediator

2. Using ipinfo API

Now, let’s use another way to get the geo information using ipinfo API. It provides geolocation data with 50,000 lookups per month for non-commercial projects, if you want more than it then you have to purchase a plan.

Use the below API in a PHP file.

Same as the above method we have to use the ipinfo API to get the location information.

Check out the output in the browser.

Get location information using ipinfo API - Clue Mediator
Get location information using ipinfo API – Clue Mediator

That’s it for today.
Thank you for reading. Happy Coding..!!

If you found value in this article,
you can support us by buying me a coffee! ☕

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *