<? // Let me start off by saying I do not take full credit for this!
// I needed a way to get my traffic's country for Adverts...
// for some reason, json_decode wasn't working, so this is an alternative.
// json_decoder function from PHP.net
// file_get_contents_curl basic data retrieval function
// how to use:
// include('country.php');
// $userCountry=getTheCountry();
// output is 2 character country code, US, CA, etc...
function file_get_contents_curl($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
function json_decoder($json)
{
$comment = false;
$out = '$x=';
for ($i=0; $i<strlen($json); $i++)
{
if (!$comment)
{
if (($json[$i] == '{') || ($json[$i] == '[')) $out .= ' array(';
else if (($json[$i] == '}') || ($json[$i] == ']')) $out .= ')';
else if ($json[$i] == ':') $out .= '=>';
else $out .= $json[$i];
}
else $out .= $json[$i];
if ($json[$i] == '"' && $json[($i-1)]!="\\") $comment = !$comment;
}
eval($out . ';');
return $x;
}
function getTheCountry(){ $ipForCo=$_SERVER['REMOTE_ADDR']; $getCo=file_get_contents_curl('http://ip2country.sourceforge.net/ip2c.php?ip='.$ipForCo.'&format=JSON'); $json_Co=json_decoder($getCo);
return $json_Co['country_code'];
} ?>
Country from IP
I was working on a advert site for a buddy, and needed to get the traffic's country code. This retrieves data (JSON format) and decodes it to get the user's country. If json_decode works on your server, you can remove json_decoder function, and change $json_Co=json_decoder($getCo); to $json_Co=json_decode($getCo);
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment