News:

SMF 2.1.4 has been released! Take it for a spin! Read more.

Main Menu

Automatically set country using geolocation

Started by cisops, August 12, 2014, 04:38:50 PM

Previous topic - Next topic

cisops

I don't know about your members, but mine don't take the time to provide their location.

Running an international forum with posts that sometimes have country-specific answers, it's good for members to know each other's location.

This little modification uses geolocation to determine the member's country and auto-populate in their profile. It uses the free API from IP Info DB. You will have to register for a free API and enter it in the code for it to work. Register for API key - http://ipinfodb.com/register.php

They also have an API that returns info down to the city level. You could easily modify this to use that if you require more accurate location info.

Use as you see fit.

Add the snippet below to the LogInOut.php in your Source folder under this line:


// You've logged in, haven't you?
updateMemberData($user_info['id'], array('last_login' => time(), 'member_ip' => $user_info['ip'], 'member_ip2' => $_SERVER['BAN_CHECK_IP']));


Add this snippet to set country location automatically:


//Customized to record members' country during logon
$apikey = 'enter-your-api-key-here';
$alltext = '';
$fd = fopen ('http://api.ipinfodb.com/v3/ip-country/?key=' . $apikey . '&ip=' . $user_info['ip'], 'r');
while ($line = fgets ($fd, 1024))
$alltext .= $line;
fclose ($fd);

$tokens = explode(";", $alltext);
$country = end($tokens);

if ($country != '')
$smcFunc['db_query']('', '
UPDATE {db_prefix}members
SET location = {string:country}
WHERE rtrim(location) = \'\' and
(member_ip = {string:ip} OR member_ip2 = {string:ip})',
array(
'country' => $country,
'ip' =>$user_info['ip'],
)
);

Advertisement: