Since IP can be spoofed, how can one build a PHP website that correctly identifies the visitor's country?
Joomla has been using below function to get IP addresses, it is very versatile good function, that can avoid possible cheats, you can use it:
function get_ip()
{
$ip = false;
if (!empty($_SERVER['HTTP_CLIENT_IP']))
{
$ip = $_SERVER['HTTP_CLIENT_IP'];
}
if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
{
$ips = explode (', ', $_SERVER['HTTP_X_FORWARDED_FOR']);
if ($ip != false)
{
array_unshift($ips,$ip);
$ip = false;
}
$count = count($ips);
# exclude IP addresses reserved for LANs
for ($i = 0; $i < $count; $i++)
{
if (!preg_match("/^(10|172\.16|192\.168)\./i", $ips[$i]))
{
$ip = $ips[$i];
break;
}
}
}
if (false == $ip AND isset($_SERVER['REMOTE_ADDR']))
{
$ip = $_SERVER['REMOTE_ADDR'];
}
return $ip;
}
That's inherently a problem given the anonymity of the internet, but spoofing IP addresses to obtain content not legally available in your country is technically a crime in most places anyways.
It's up to you to make every reasonable effort to ensure your site follows distribution restrictions on media and information, but there are some things that are just impractical to guard against. The closest you could get is by doing an actual physical address verification such as a billing address on a credit card or physically mailing someone a pin number for registration, but both of those options incur expenses on behalf of either the user or yourself.