views:

227

answers:

2

Since IP can be spoofed, how can one build a PHP website that correctly identifies the visitor's country?

A: 

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;
}
Sarfraz
@Sarfraz, thank you. I'll give it a try. Not very sure what the regex filters out though.
cheapskate
This code is even easier to defeat than using a proxy: Just set the header on your outgoing request to an allowed IP. No proxy needed. This is well known, eg for watching Comedy Central outside the US.
McPherrinM
You might be right, but we have not seen any issue with joomla while using that function. If you have seen one, please let us know. thanks
Sarfraz
To elaborate: This code is a start. What you need to verify that that *AND* REMOTE_ADDR are in your country.
McPherrinM
Here is an example of how to get around the code above, in very concrete terms: http://ohryan.ca/blog/2009/08/15/how-to-watch-comedy-central-videos-from-canada/
McPherrinM
@WaffleMatt, can you kindly explain your last reply? Thanks.
cheapskate
+1  A: 

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.

WarrenB