Need help with geolocation script

King.

New member
Dec 26, 2010
613
6
0
I'm using the geoplugin.com script for my php redirect. At the moment I'm redirecting based off country ip, but I also want to be able to do it based on city and state. Here's what I have atm:

PHP:
<?php
//country code redirect
require_once('geoplugin.class.php');
$geoplugin = new geoplugin();
$geoplugin->locate();
$country_code = $geoplugin->countryCode;
switch($country_code) {
case 'US':
header('Location: http://www.123.com/1/');
exit;
case 'CA':
header('Location: http://www.123.com/2/');
exit;
default: // exceptions
header('Location: http://www.123.com/0/');
exit;
}
?>
 


geoPlugin's free and easy PHP geolocation webservice explained

That page outlines the values that you get. So you would essentially need to get $geoplugin->city for the city and $geoplugin->state for the state.

So one way to do it is like this which is fucking messy as hell and very tedious to add new cities.

Code:
require_once('geoplugin.class.php');
$geoplugin = new geoplugin();

// lets get the location
$geoplugin->locate();

switch($geoplugin->countryCode) {
	case 'US':
		switch ($geoplugin->state) {
			case 'FL':
				switch ($geoplugin->city) {
					case 'Miami':
						header('Location: http://www.123.com/us/fl/miami/');
						exit();
					break;
					default:
						header('Location: http://www.123.com/us/fl/');
						exit();
					break;
				}
			break;
			default:
				header('Location: http://www.123.com/us/');
				exit();
			break;
		}
	break;
	case 'CA':
		header('Location: http://www.123.com/ca/');
		exit();
	break;
	default: // exceptions
		header('Location: http://www.123.com/');
		exit();
	break;
}

If you need full flexibility use a database to pull out the city / state / country and have a field that specifies the URL.

Code:
require_once('geoplugin.class.php');
require_once('mydatabase.class.php');

$geoplugin = new geoplugin();
$db = new database();

// lets get the location
$geoplugin->locate();

// since $geoplugin is not a very big object just send it all, on the db side just extract the fields you need.
$result = $db->getGeoUrl($geoplugin);

if($result){
	header('Location:' . $result['url']); exit();
} else {
	header('Location: http://www.123.com'); exit();
}

Enjoy!