This is a quick little function that uses cURL to scrape a third party website to get information about a users's location. I've noticed that the response may not always be very accurate, so I wouldn't recommend this for anything where the location actually matters.
function location_information($ip_address) {
#create an array of fields we will be searching for. This array is used later
$fields = array ("Country","State/Province","City","Zip or postal code","Latitude","Longitude","Timezone","Local time","Hostname");
#url of the site we'll be scraping
$url = 'http://ipinfodb.com/ip_locator.php?ip=' . urlencode($ip_address);
#initialize curl
$ch = curl_init();
#set array of curl options
$curl_opt = array(
CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_HEADER => 0,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_USERAGENT => $_SERVER['HTTP_USER_AGENT'], #send the user's useragent, just in case they start blocking requests from servers
CURLOPT_URL => $url,
CURLOPT_TIMEOUT => 1,
CURLOPT_REFERER => 'http://' . $_SERVER['HTTP_HOST'],
);
#set the options
curl_setopt_array($ch, $curl_opt);
#run curl, get content back in a string
$content = curl_exec($ch);
if (!is_null($curl_info)) {
$curl_info = curl_getinfo($ch);
}
#close curl
curl_close($ch);
#loop through array of fields we're looking for, pull out corresponding values
foreach($fields as $field) {
iif ( preg_match("{<li>$field : ([^<]*)</li>}i", $content, $regs) ) {
$location[$field] = $regs[1]; }
}}
#return array of location information
return $location;
}
Usage is as follows:
print_r(location_information($_SERVER['REMOTE_ADDR']));