Php get location from ip

The following is a modified version of a snippet I found that uses http://ipinfodb.com/ip_locator.php to get its information. Keep in mind, you can also apply for an API key with them and use the API directly to get the information supplied as you see fit.

Snippet

function detect_location($ip=NULL, $asArray=FALSE) {
    if (empty($ip)) {
        if (!empty($_SERVER['HTTP_CLIENT_IP'])) { $ip = $_SERVER['HTTP_CLIENT_IP']; }
        elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; }
        else { $ip = $_SERVER['REMOTE_ADDR']; }
    }
    elseif (!is_string($ip) || strlen($ip) < 1 || $ip == '127.0.0.1' || $ip == 'localhost') {
        $ip = '8.8.8.8';
    }

    $url = 'http://ipinfodb.com/ip_locator.php?ip=' . urlencode($ip);
    $i = 0; $content; $curl_info;

    while (empty($content) && $i < 5) {
        $ch = curl_init();
        $curl_opt = array(
            CURLOPT_FOLLOWLOCATION => 1,
            CURLOPT_HEADER => 0,
            CURLOPT_RETURNTRANSFER  => 1,
            CURLOPT_URL => $url,
            CURLOPT_TIMEOUT => 1,
            CURLOPT_REFERER => 'http://' . $_SERVER['HTTP_HOST'],
        );
        if (isset($_SERVER['HTTP_USER_AGENT'])) $curl_opt[CURLOPT_USERAGENT] = $_SERVER['HTTP_USER_AGENT'];
        curl_setopt_array($ch, $curl_opt);
        $content = curl_exec($ch);
        if (!is_null($curl_info)) $curl_info = curl_getinfo($ch);
        curl_close($ch);
    }

    $araResp = array();
    if (preg_match('{
  • City : ([^<]*)
  • }i', $content, $regs)) $araResp['city'] = trim($regs[1]); if (preg_match('{
  • State/Province : ([^<]*)
  • }i', $content, $regs)) $araResp['state'] = trim($regs[1]); if (preg_match('{
  • Country : ([^<]*)}i', $content, $regs)) $araResp['country'] = trim($regs[1]); if (preg_match('{
  • Zip or postal code : ([^<]*)
  • }i', $content, $regs)) $araResp['zip'] = trim($regs[1]); if (preg_match('{
  • Latitude : ([^<]*)
  • }i', $content, $regs)) $araResp['latitude'] = trim($regs[1]); if (preg_match('{
  • Longitude : ([^<]*)
  • }i', $content, $regs)) $araResp['longitude'] = trim($regs[1]); if (preg_match('{
  • Timezone : ([^<]*)
  • }i', $content, $regs)) $araResp['timezone'] = trim($regs[1]); if (preg_match('{
  • Hostname : ([^<]*)
  • }i', $content, $regs)) $araResp['hostname'] = trim($regs[1]); $strResp = ($araResp['city'] != '' && $araResp['state'] != '') ? ($araResp['city'] . ', ' . $araResp['state']) : 'UNKNOWN'; return $asArray ? $araResp : $strResp; }

    To Use

    detect_location();
    //  returns "CITY, STATE" based on user IP
    
    detect_location('xxx.xxx.xxx.xxx');
    //  returns "CITY, STATE" based on IP you provide
    
    detect_location(NULL, TRUE);    //   based on user IP
    //  returns array(8) { ["city"] => "CITY", ["state"] => "STATE", ["country"] => "US", ["zip"] => "xxxxx", ["latitude"] => "xx.xxxxxx", ["longitude"] => "-xx.xxxxxx", ["timezone"] => "-07:00", ["hostname"] => "xx-xx-xx-xx.host.name.net" }
    
    detect_location('xxx.xxx.xxx.xxx', TRUE);   //   based on IP you provide
    //  returns array(8) { ["city"] => "CITY", ["state"] => "STATE", ["country"] => "US", ["zip"] => "xxxxx", ["latitude"] => "xx.xxxxxx", ["longitude"] => "-xx.xxxxxx", ["timezone"] => "-07:00", ["hostname"] => "xx-xx-xx-xx.host.name.net" }
    

    Home  »  PHP   »   Get Geolocation (Country, Latitude, and Longitude) from IP Address using PHP

    Geolocation provides information about the geographic location of a user. Specifically, the IP address is used by the geolocation service to determine the location. To track the visitor’s location, the first thing needed is an IP address. Based on the IP address, we can collect the geolocation info of the visitor. The PHP $_SERVER variable is the easiest way to get the user’s IP address. Based on the visitor’s IP address, you can detect the location with latitude and longitude using PHP. In this tutorial, we will show you how to get location from IP address using PHP.

    The Geolocation API is an instant way to find the location of a user by IP address. You can use a free Geolocation API in PHP to fetch location information from an IP address. This example script will use IP Geolocation API to get location, country, region, city, latitude, and longitude from IP address using PHP.

    Get IP Address of User with PHP

    Use the REMOTE_ADDR index of $_SERVER to get the current user’s IP address in PHP.

    $userIP $_SERVER['REMOTE_ADDR'];

    Get Location from IP Address using PHP

    Use the IP Geolocation API to get the user’s location from IP using PHP.

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

    There are various info is available about geolocation in API response. Some of the most useful location details are:

    • Country Name (country_name)
    • Country Code (country_code)
    • Region Code (region_code)
    • Region Name (region_name)
    • City (city)
    • Zip Code (zip_code)
    • Latitude (latitude)
    • Longitude (longitude)
    • Time Zone (time_zone)
    // IP address 
    $userIP '162.222.198.75'; // API end URL
    $apiURL 'https://freegeoip.app/json/'.$userIP; // Create a new cURL resource with URL
    $ch curl_init($apiURL); // Return response instead of outputting
    curl_setopt($chCURLOPT_RETURNTRANSFERtrue); // Execute API request
    $apiResponse curl_exec($ch); // Close cURL resource
    curl_close($ch); // Retrieve IP data from API response
    $ipData json_decode($apiResponsetrue);

    if(!empty(

    $ipData)){
        
    $country_code $ipData['country_code'];
        
    $country_name $ipData['country_name'];
        
    $region_code $ipData['region_code'];
        
    $region_name $ipData['region_name'];
        
    $city $ipData['city'];
        
    $zip_code $ipData['zip_code'];
        
    $latitude $ipData['latitude'];
        
    $longitude $ipData['longitude'];
        
    $time_zone $ipData['time_zone'];

             echo

    'Country Name: '.$country_name.'
    '
    ;
        echo 
    'Country Code: '.$country_code.'
    '
    ;
        echo 
    'Region Code: '.$region_code.'
    '
    ;
        echo 
    'Region Name: '.$region_name.'
    '
    ;
        echo 
    'City: '.$city.'
    '
    ;
        echo 
    'Zipcode: '.$zip_code.'
    '
    ;
        echo 
    'Latitude: '.$latitude.'
    '
    ;
        echo 
    'Longitude: '.$longitude.'
    '
    ;
        echo 
    'Time Zone: '.$time_zone;
    }else{
        echo 
    'IP data is not found!';
    }
    ?>

    For better usability, you can group all the code in a function.

    • The following IPtoLocation() function returns geolocation data from IP address.
    function IPtoLocation($ip){ 
        
    $apiURL 'https://freegeoip.app/json/'.$ip; // Make HTTP GET request using cURL
        
    $ch curl_init($apiURL);
        
    curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
        
    $apiResponse curl_exec($ch);
        if(
    $apiResponse === FALSE) {
            
    $msg curl_error($ch);
            
    curl_close($ch);
            return 
    false;
        }
        
    curl_close($ch); // Retrieve IP data from API response
        
    $ipData json_decode($apiResponsetrue); // Return geolocation data
        
    return !empty($ipData)?$ipData:false;
    }

    Call IPtoLocation() and pass the IP address in the first argument.

    $userIP '162.222.198.75'; 
    $locationInfo IPtoLocation($userIP);

    Are you want to get implementation help, or modify or enhance the functionality of this script? Submit Paid Service Request

    If you have any questions about this script, submit it to our QA community - Ask Question

    How can I get current location from IP address in PHP?

    From PHP.net: The GeoIP extension allows you to find the location of an IP address. City, State, Country, Longitude, Latitude, and other information as all, such as ISP and connection type can be obtained with the help of GeoIP. This is just a php module for the MaxMind database, which is payware.

    Can you get location from IP address?

    The IP address routes Internet traffic to your computer. To clarify, it does not reveal your location. If someone was able to get your IP address they could learn a bit about your Internet service, such as which provider you use to connect to the internet, but they really can't locate you, your home, or your office.

    How get lat long from IP address in PHP?

    PHP does not have the in-built support for that. You could make use of third party libraries like ip2location to grab the longitude and latitude from the ip address. Sidenote : Determining the latitude - longitude through an IP Address may not fetch you accurate information.

    How do I find the geo location of an IP address?

    Just send HTTP GET request to https://api.ipgeolocationapi.com with different parameters and get the JSON result. For example, the following HTTP GET request will give you a location of the specified IP address. The following request returns the country information specified by the ISO country code.