问题
How can I get the user's country and forward them to a URL based on it?
I am looking specifically at Australia, New Zealand, USA, UK and Other.
Preferably with PHP, but can use Javascript if necessary.
回答1:
This may help you to get country then you can redirect accordingly.
<?PHP
function visitor_country()
{
$client = @$_SERVER['HTTP_CLIENT_IP'];
$forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
$remote = $_SERVER['REMOTE_ADDR'];
$result = "Unknown";
if(filter_var($client, FILTER_VALIDATE_IP))
{
$ip = $client;
}
elseif(filter_var($forward, FILTER_VALIDATE_IP))
{
$ip = $forward;
}
else
{
$ip = $remote;
}
$ip_data = @json_decode(file_get_contents("http://www.geoplugin.net/json.gp?ip=".$ip));
if($ip_data && $ip_data->geoplugin_countryName != null)
{
$result = $ip_data->geoplugin_countryName;
}
return $result;
}
echo visitor_country(); // Output Coutry name [Ex: United States]
?>
OR in Javascript.
<html>
<head>
<script language="JavaScript" src="http://www.geoplugin.net/javascript.gp" type="text/javascript"></script>
</head>
<body>
<script language="Javascript">
document.write("Welcome to our visitors from "+geoplugin_city()+", "+geoplugin_countryName());
// window.location = "http://www.yoururl.com"; /* you can forward user to url using this line of code according to your conditions
</script>
</body>
</html>
回答2:
Please check the below link.
How can I detect visitor's country and redirect he/she to an specific website?
May be it will help you.. :)
回答3:
You can use PECL's geoip_country_by_name() with the user's ip address to get their country:
<?php
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}
$country = geoip_country_name_by_name($ip);
if ($country) {
echo 'This host is located in: ' . $country;
//header("Location: " . $somelocation);
}
?>
来源:https://stackoverflow.com/questions/20185343/how-to-get-users-country-and-forward-to-url