Plug-in PHP Chapter 12, Plug-in 91 (Click on the icon to view the source for copy and pasting)
<?php // Plug-in 91: Get Country From IP

// This is an executable example with additional code supplied
// To obtain just the plug-ins please click on the Download link

$ip     = '127.0.0.1';
$result = PIPHP_GetCountryFromIP($ip);

if (!$result) echo "Could not identify location for '$ip'.";
else          echo "The location of '$ip' is: $result.";

function PIPHP_GetCountryFromIP($ip)
{
   // Plug-in 91: Get Country From IP
   //
   // This plug-in returns the country associated with a
   // supplied IP number. It requires this argument:
   //
   //    $ip: An IP address

   $iptemp = explode('.', $ip);
   $ipdec  = $iptemp[0] * 256 * 256 * 256 +
             $iptemp[1] * 256 * 256 +
             $iptemp[2] * 256 +
             $iptemp[3];
   $file  = file_get_contents('ips.txt');
   if (!strlen($file)) return FALSE;

   $lines = explode("\n", $file);

   foreach($lines as $line)
   {
      if (strlen($line))
      {
         $parts = explode(',', trim($line));

         if ($ipdec >= $parts[0] && $ipdec <= $parts[1])
            return $parts[2];
      }
   }

   return FALSE;
}

?>