Tuesday, January 20, 2015

PHP Tip - Getting location of visitor

Very often, you want to know the location of your web site visitor's, such as country, region, and other location information. You can do so via passing the IP address of the user to this free site: http://www.geoplugin.net/json.gp. It will then return you a JSON string containing detailed location information pertaining to the specified IP address.

To use this site in PHP, you can create a function, like the following:

function getLocationUsingIP($ip) {        
    $result = @json_decode(file_get_contents(
        "http://www.geoplugin.net/json.gp?ip=" . $ip));
    if($result && $result->geoplugin_countryName != null)
        $location['region'] = $result->geoplugin_region;
        $location['city'] = $result->geoplugin_city;
        $location['country'] = $result->geoplugin_countryCode;
        $location['latitute'] = $result->geoplugin_latitude;
        $location['longitude'] = $result->geoplugin_longitude;
    return $location;

To call it, call the function by passing the IP address of the user (obtainable via $_SERVER[REMOTE_ADDR]):

    $location = getLocationUsingIP($_SERVER[REMOTE_ADDR]);    
    echo $location['region'] . "<br/>";
    echo $location['city'] . "<br/>";
    echo $location['country'] . "<br/>";
    echo $location['latitute'] . "<br/>";
    echo $location['longitude'] . "<br/>";

To learn more about PHP and MySQL programming, enrol in the WEB103 - Web Development using PHP and MySQL course (2-days).
Course Fee
S$1097 (nett; no GST)
If your company is sponsoring you for the training, your company can enjoy 400% tax deductions/ allowances and/or 60% cash payout for investment in innovation and productivity improvements under the Productivity and Innovation Credit (PIC) scheme. For more details, check out the Productivity and Innovation Credit page. 
Start DateEnd DateDetailsCategory
Tue Feb 03 2015Wed Feb 04 2015PDF
Thu Mar 05 2015Fri Mar 06 2015PDF
Mon Apr 06 2015Tue Apr 07 2015PDF
Bayview Hotel Singapore
30 Bencoolen Street
Singapore 189621  

If your company requires in-house training, you can contact us to customize the topics to meet your training requirements. We train worldwide! We have conducted customized classes in the United States, Norway, Denmark, Japan, China, Hong Kong, Taiwan, and Thailand.

No comments: