05
Days
23
Hours
59
Minutes
59
Seconds


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>
try
{
  if (!function_exists('rsform_get_ip'))
  {
    function rsform_get_ip($ip)
    {
      // Get the HTTP transport
      $http = Joomla\CMS\Http\HttpFactory::getHttp();
      // Create the URL for the API request
      $url = 'http://ip-api.com/json/'.urlencode($ip);
      // Get response
      $response = $http->get($url);
      // Check if request is successful, a 200 code should be received.
      if ($response->code == 200)
      {
      $json = json_decode($response->body, true);
      if (isset($json['country']))
      {
        return $json['country'];
      }
      }
      return 'Unknown';
    }
  }
  // Let's cache results for better performance
  $cache = Joomla\CMS\Factory::getCache();
  $cache->setCaching(true);
  // Grab the IP
  $ip = Joomla\CMS\Factory::getApplication()->input->server->getString('REMOTE_ADDR');
  // Call function through cache
  return $cache->get('rsform_get_ip', $ip);
} catch (Exception $e) {}
//</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}.

18 persons found this article helpful.


Was this article helpful?

Yes No
Sorry about that