Display the country from which the form is being submitted

In this article we will describe how to get the IP address of a submitting client and displaying the country which it belongs to.

In order to achieve this functionality, just create a hidden field with the following code placed in the "Default Value" area.

//<code>
//<code>
try
{
  // Let's cache results for better performance
  $cache = JFactory::getCache();
  $cache->setCaching(true);
  // Grab the IP
  $ip = JFactory::getApplication()->input->server->getString('REMOTE_ADDR');
  // Call function through cache
  return $cache->get('rsform_get_ip', $ip);
} catch (Exception $e) {}
if (!function_exists('rsform_get_ip'))
{
  function rsform_get_ip($ip)
  {
    // Get the HTTP transport
    $http = JHttpFactory::getHttp();
    // Create the URL for the API request
    $url = 'http://api.geoiplookup.net/?query='.urlencode($ip);
    // Get response
    $response = $http->get($url);
    // Check if request is successful, a 200 code should be received.
    if ($response->code == 200)
    {
    if (preg_match('/<countryname>(.*?)<\/countryname>/', $response->body, $match))
    {
    return $match[1];
    }
    }
    return 'Unknown';
  }
}
//</code>
Let's say, for example that you named your hidden field "location". To display the calculated value in the "Thank you" page or email just use this syntax: {location:value}.

16 persons found this article helpful.


Was this article helpful?

Yes No
Sorry about that