Skip to content
Related Articles

Related Articles

How to get Geolocation using PHP-cURL from IP Address ?

Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 17 Jun, 2021
Improve Article
Save Article

Geolocation refers to the identification of the geographical location of a user or computer device. 

In this article, we will create a web page where the user can enter the IP Address of any device, and then the server will provide Geolocation of the IP address fetching the following details using the IP Geolocation API.

  • Continent Name
  • Country Name
  • Country Alpha-2 Code
  • Country Alpha-3 Code
  • Country Numeric Code
  • Country International Call Prefix Code
  • Currency Code
  • Latitude
  • Longitude


  • Call API via HTTP GET request using cURL in PHP.
  • Convert API JSON response to array using PHP json_decode() function.
  • Retrieve IP data from API response.

Example: The following code gets the location from IP address using PHP cURL.


    $userIP = $_POST['ip']; 
    $apiURL = ''.$userIP;  
    $ch = curl_init($apiURL); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
    $apiResponse = curl_exec($ch); 
    $ipData = json_decode($apiResponse, true); 
        $continent = $ipData['continent']; 
        $country_code_alpha2 = $ipData['alpha2']; 
        $country_code_alpha3 = $ipData['alpha3']; 
        $country_name = $ipData['name']; 
        $country_code_numeric = $ipData['country_code']; 
        $international_prefix = $ipData['international_prefix']; 
        $currency_code = $ipData['currency_code']; 
        $latitude = $ipData['geo']['latitude']; 
        $longitude = $ipData['geo']['longitude']; 
        echo 'Continent Name: '.$continent.'<br/>'
        echo 'Country Name: '.$country_name.'<br/>'
        echo 'Country Alpha-2 Code: '.$country_code_alpha2.'<br/>'
        echo 'Country Alpha-3 Code: '.$country_code_alpha3.'<br/>'
        echo 'Country Numeric Code: '.$country_code_numeric.'<br/>'
        echo 'Country International Call Prefix Code: '
                . $international_prefix.'<br/>'
        echo 'Currency Code: '.$currency_code.'<br/>'
        echo 'Latitude: '.$latitude.'<br/>'
        echo 'Longitude: '.$longitude
        echo 'Not a valid IP';
<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta name="viewport" content=
        "width=device-width, initial-scale=1.0">
    <title>Get Location</title>
    <h1>Get Location Using IP Address</h1>
    <form method='post' enctype='multipart/form-data'>
        <label>Give IP address for check location</label>
        <input type='text' name='ip' />
        <input type='submit' value='Submit' name='submit' />
        <a href="index.php">Reset</a>


  • Valid IP address: When the user enters valid IP address.
  • Invalid IP address: When the user enters an invalid IP address in the input text control.

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!