javascript - Geolocation API to detect the user's country? -
i need detect user's country , display data users select countries.
afaik, accurate way using api. 1 ? there's lot of commercial offer, seems bit overkill country (i don't care long/lat or cities)
what accurate way without spending hundreds of dollars yearly ?
use simple php function , information of user's country,city etc. passing ip address of user..
function ip_info($ip = null, $purpose = "location", $deep_detect = true) { $output = null; if (filter_var($ip, filter_validate_ip) === false) { $ip = $_server["remote_addr"]; if ($deep_detect) { if (filter_var(@$_server['http_x_forwarded_for'], filter_validate_ip)) $ip = $_server['http_x_forwarded_for']; if (filter_var(@$_server['http_client_ip'], filter_validate_ip)) $ip = $_server['http_client_ip']; } } $purpose = str_replace(array("name", "\n", "\t", " ", "-", "_"), null, strtolower(trim($purpose))); $support = array("country", "countrycode", "state", "region", "city", "location", "address"); $continents = array( "af" => "africa", "an" => "antarctica", "as" => "asia", "eu" => "europe", "oc" => "australia (oceania)", "na" => "north america", "sa" => "south america" ); if (filter_var($ip, filter_validate_ip) && in_array($purpose, $support)) { $ipdat = @json_decode(file_get_contents("http://www.geoplugin.net/json.gp?ip=" . $ip)); if (@strlen(trim($ipdat->geoplugin_countrycode)) == 2) { switch ($purpose) { case "location": $output = array( "city" => @$ipdat->geoplugin_city, "state" => @$ipdat->geoplugin_regionname, "country" => @$ipdat->geoplugin_countryname, "country_code" => @$ipdat->geoplugin_countrycode, "continent" => @$continents[strtoupper($ipdat->geoplugin_continentcode)], "continent_code" => @$ipdat->geoplugin_continentcode ); break; case "address": $address = array($ipdat->geoplugin_countryname); if (@strlen($ipdat->geoplugin_regionname) >= 1) $address[] = $ipdat->geoplugin_regionname; if (@strlen($ipdat->geoplugin_city) >= 1) $address[] = $ipdat->geoplugin_city; $output = implode(", ", array_reverse($address)); break; case "city": $output = @$ipdat->geoplugin_city; break; case "state": $output = @$ipdat->geoplugin_regionname; break; case "region": $output = @$ipdat->geoplugin_regionname; break; case "country": $output = @$ipdat->geoplugin_countryname; break; case "countrycode": $output = @$ipdat->geoplugin_countrycode; break; } } } return $output; } ?>
Comments
Post a Comment