Explore our IP Address Database Downloads for instant access to our IP address insights

Learn more
4 years ago by IPinfo Team 6 min read

How to get IP geolocation in PHP with IPinfo API

IP address geolocation in PHP

There are many ways to use geolocation data, from personalizing website experiences to improving matchmaking in online games. For instance, you can easily change the content of a website page based on the visitor's country. The IPinfo Geolocation API makes it's easy to get started.

The premise of using an API relies on making requests. However, every programming language has its own way to make a request, from built-in functions to libraries to make things even easier.

Here, we're going to show you how to get started using the IPinfo APIs by getting IP geolocation in PHP built-in functions and libraries.

Request, Response, and their Headers

Before we jump to the PHP code, let's make a simple request using curl and see what happens.

curl is a command-line program that can be used to make requests quickly and can also help debug them. It's available by default on Windows 10, macOS, and most Linux distributions.

(Note: if you're using PowerShell make sure to use curl.exe command instead of curl since the latter is an alias for Invoke-WebRequest PowerShell command.)

If you don't have an API token you can sign up at IPinfo and get one with the free plan that offers 50,000 requests/month.

Now let's see a quick example of curl using the IPinfo geolocation API. Here's the response:

curl https://ipinfo.io/8.8.8.8?token=your_access_token
{
  "ip": "8.8.8.8",
  "hostname": "dns.google",
  "anycast": true,
  "city": "Mountain View",
  "region": "California",
  "country": "US",
  "loc": "37.4056,-122.0775",
  "org": "AS15169 Google LLC",
  "postal": "94043",
  "timezone": "America/Los_Angeles"
}

The details in this response are the ones available on the free plan, but you can see the full potential of the API in the Responses documentation.

It's also worth taking a look at the headers, both the requests and responses. curl can help with that.

To get the response headers, simply use the -I or --head option:

curl -I https://ipinfo.io/8.8.8.8?token=your_access_token
HTTP/1.1 200 OK
Date: Tue, 27 Apr 2021 14:42:29 GMT
Content-Type: application/json; charset=utf-8
Content-Length: 304
Vary: Accept-Encoding
Access-Control-Allow-Origin: *
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block
X-Content-Type-Options: nosniff
Referrer-Policy: strict-origin-when-cross-origin
Via: 1.1 google

From the response headers, you can see that the request was successful. Plus, you can view the content type, which is useful when working with APIs.

Get accurate geolocation data

Enhance user experience and strengthen your security with rich geolocation data.

Learn More
Get accurate geolocation data

Next, to get the request headers, you need to use the -v option (short for --verbose):

curl.exe -I https://ipinfo.io/8.8.8.8?token=your_access_token
[...]
> GET /8.8.8.8 HTTP/1.1
> Host: ipinfo.io
> User-Agent: curl/7.55.1
> Accept: */*
[...]

We aren't going through every detail of the headers here, but it's important to know what is required in the request headers. If you want to learn more about HTTP and its requests in-depth, the RFC7230 is a great place to start.

But in short, here's what is required when making the request:

  • Method, in this case, the "GET" method;
  • Path, in this case, "/8.8.8.8";
  • HTTP version, in this case, "HTTP/1.1";
  • Host, in this case, "ipinfo.io".

curl gives a good example of what should be in the request. From the response headers (and the response itself), we can see that it's working as intended.

Now, let's see how to translate this to PHP and get the geolocation data in this programming language.

As we mentioned previously, programming languages can have more than one way to make requests like this. This is the case with PHP. Let's go over some of the ways to make requests using PHP.

file_get_contents()

The file_get_contents function is the simplest way to make a request with PHP. Basically, to make a request and get the geolocation data from IPinfo API with this function, all you need is to pass the URL as a parameter:

<?php
// Set the API token, you can get one by signing up at <https://ipinfo.io/signup>
$token = "your_access_token";
// Make the request passing the IP and token and store the result in a variable
$geolocation_data = file_get_contents("https://ipinfo.io/8.8.8.8?token=$token");
// Print the result as a string
echo "IP geolocation in PHP with file_get_contents()";
echo $geolocation_data;
?>

The result:

{ "ip": "8.8.8.8", "hostname": "dns.google", "anycast": true, "city": "Mountain View", "region": "California", "country": "US", "loc": "37.4056,-122.0775", "org": "AS15169 Google LLC", "postal": "94043", "timezone": "America/Los_Angeles" }

Note that by default the response is formatted as JSON, but file_get_contents reads the content to String. So to handle the data properly, you would need to parse to JSON. This can be done using the json_decode() function:

<?php echo "<p>IP geolocation in PHP with file_get_contents:</p>";
// Set the IP to be used in the request
$ip = "8.8.8.8";
// Set the API token, you can get one for free by signing up at https://ipinfo.io/signup
$token = "your_access_token";
// Make the request and store it in a variable as a string
$ipinfo = file_get_contents("https://ipinfo.io/" . $ip . "?token=" . $token);
// Convert the string into object
$json = json_decode($ipinfo);
// Print a property of the object
echo "Geolocation data in PHP with file_get_contents:";
echo "Country: " . $json->country;
?>

The result:

Geolocation data in PHP with file_get_contents:
Country: US

Now you can access each property and get their fields individually.

(Note: the file_get_contents() function requires allow_url_fopen to be true to work.)

PHP's cURL

Another way to get the geolocation data in PHP is using its own cURL library. This library allows the use of more options and can offer better performance. However, you may need to install it separately since it's not available in every PHP install.

The PHP's cURL library has many options, but we're going to start with the basic usage. In this case, it is a request from a registered user. So a token is required for the authentication:

// Set the API endpoint
$endpoint = "<https://ipinfo.io/>";
// Set the IP address
$ip = "8.8.8.8";
// Set the API token, you can get one by signing up at <https://ipinfo.io/signup>
$token = "your_access_token";

// Initialize curl session
$curl = curl_init($endpoint . $ip);
// Set curl options for token and to return content as string
curl_setopt($curl, CURLOPT_USERPWD, $token);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
// Execute the session, making the request
$response = curl_exec($curl);
// close cURL session, and free up system resources
curl_close($curl);

echo "IP geolocation in PHP with PHP's cURL:";
echo PHP_EOL;
// Converts JSON string into a PHP object
$json = json_decode($response);
// Print some details of the API by accessing object properties
echo "Data for $ip: $json->city, $json->region, $json->country";

The result:

Geolocation data in PHP with PHP's cURL:
Data for 8.8.8.8: Mountain View, California, US

IPinfo PHP Client Library

Alternatively, you could use the official IPinfo PHP Client Library, which does the heavy lifting and makes it even easier to get IP geolocation data in PHP. The library is open source under the Apache license. It uses the guzzle PHP HTTP client under the hood - one of the most popular PHP libraries.

Besides providing the geolocation data (city, region, country, postal code, latitude, and longitude), the library makes it easier to get details like:

Since these libraries are maintained by the IPinfo team, users can rely on this accurate geolocation data for their use case.

To use the library, you need to install it, which can be done with composer, the most popular dependency manager for PHP.

composer require ipinfo/ipinfo

From here, you can already use it after including the autoload.php file:

// Get your API token by signing up at <https://ipinfo.io/signup>
$access_token = "your_access_token";
// Create a new object from the IPinfo class, passing the token as a parameter
$client = new IPinfo($access_token);
// Declare a variable with the IP
$ip_address = "8.8.8.8";
// Call the getDetails() method from the IPinfo object passing the IP address
$details = $client->getDetails($ip_address);

echo "IP geolocation in PHP with IPinfo PHP Client Library for $ip_address:";
echo PHP_EOL;

// Print the array with all details in the response
echo "All details:" . PHP_EOL;
print_r($details->all);

// Print the specific details from Details object
echo "Some details:" . PHP_EOL;
echo $details->city . PHP_EOL;
echo $details->region  . PHP_EOL;
echo $details->country  . PHP_EOL;
echo $details->loc . PHP_EOL;

The result:

All details:
Array
(
    [ip] => 8.8.8.8
    [hostname] => dns.google
    [anycast] => 1
    [city] => Mountain View
    [region] => California
    [country] => US
    [loc] => 37.4056,-122.0775
    [org] => AS15169 Google LLC
    [postal] => 94043
    [timezone] => America/Los_Angeles
    [country_name] => United States
    [latitude] => 37.4056
    [longitude] => -122.0775
)
Some details:
Mountain View
California
US
37.4056,-122.0775

Another benefit of using the IPinfo Client Library for IP geolocation in PHP is to have the option to use caching. With this feature, the values will be cached in memory for a specified time, thus reducing resource usage.

There's also an official library for the Laravel framework. So if you're looking for a way to get IP geolocation data in PHP with Laravel, this can be very helpful.

To summarize, it's easy to get IP geolocation in PHP. And although there are multiple ways to retrieve this data, the best way will be the one that fits your specific project and use case.

Regardless of which programming language you need to use, you can always refer to the examples in the API documentation to get help with your implementation. If you need help or have questions, just shoot us a message here.

About the author

IPinfo Team

IPinfo Team

Internet Data Expert