Skip to content

Instantly share code, notes, and snippets.

@alash3al
Last active September 14, 2015 13:16
Show Gist options
  • Save alash3al/3c5db47b02303dad29c0 to your computer and use it in GitHub Desktop.
Save alash3al/3c5db47b02303dad29c0 to your computer and use it in GitHub Desktop.
Extract the "most valid" ip-address from the client-request, then uses a `GEO-IP` service to fetch its information .
<?php
/*
* Extract the "most valid" ip-address from the client-request
* then uses a `GEO-IP` service to fetch its information .
*
* To extract the "most valid" ip-address, it loops over all http-headers
* from the client-request, then gets the ip that matches this pattern
* "^([0-9]+){3}\.([0-9]+){3}\.([0-9]+){3}\.([0-9]+){3}$"
* this is done becaouse each proxy server "may" send a http-header
* i.e: "HTTP_X_FORWARDED_FOR", "HTTP_VIA" ... etc .
*
* @author Mohammed Al Ashaal "<alash3al@{fb, github}, m7medalash3al@twitter>"
* @license MIT License
* @return stdClass
* @uses "www.telize.com" geo-ip api
* @example `print "<pre>" . print_r(inspectUserLocation(), 1) . "</pre>";`
*/
function inspectUserLocation()
{
// just a shortcut
$s = &$_SERVER;
// the default ip address
$ip = $s['REMOTE_ADDR'];
// don't use it on localhost
if ( $ip == '127.0.0.1' ) {
throw new Exception("Don't use me on localhost :)");
}
// extract all http-ip-address that passed by any proxy
foreach ( $s as $k => $v ) {
if ( (stripos($k, "http_") !== false) && (preg_match("/^([0-9]+){3}\.([0-9]+){3}\.([0-9]+){3}\.([0-9]+){3}$/", $v)) ) {
$ip = $v;
break;
}
}
// done
return json_decode(file_get_contents(sprintf("http://www.telize.com/geoip/%s", $ip)));
}
@alash3al
Copy link
Author

Example

<?php

print "<pre>" . print_r(inspectUserLocation(), 1) . "</pre>";

Result

stdClass Object
(
    [dma_code] => 0
    [ip] => 62.210.94.133
    [asn] => AS12876
    [latitude] => 48.86
    [country_code] => FR
    [offset] => 2
    [country] => France
    [isp] => ONLINE S.A.S.
    [timezone] => Europe/Paris
    [area_code] => 0
    [continent_code] => EU
    [longitude] => 2.35
    [country_code3] => FRA
)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment