Last active
September 14, 2015 13:16
-
-
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 .
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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))); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example
Result