Last active
September 6, 2015 21:34
-
-
Save vhdm/d56d980c4fb0648ea86b to your computer and use it in GitHub Desktop.
Get country from ip
This file contains 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
<? | |
// 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']; | |
} | |
echo getTheCountry(); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment