2

i can use this script easily when users land on site.com/redirect.php they get redirected to appropriate TLD according to geo IP but when i add this code in 'index.php' it creates a redirect loop. Can you help me modify it so that it doesn't create loop. right now this 'break' is not helping..

<?php
// Next two lines are for Beyond Hosting
// Don't forget to change your-domain
require_once '/home/your-domain/php/Net/GeoIP.php';
$geoip = Net_GeoIP::getInstance('/home/your-domain/php/Net/GeoIP.dat');

// Next two lines are for HostGator
require_once 'Net/GeoIP.php';
$geoip = Net_GeoIP::getInstance('GeoIP.dat');

try {
  $country = $geoip->lookupCountryCode($_SERVER['REMOTE_ADDR']);

  switch((string)$country) {
    case 'AU':
      $url = "http://www.site.au";
      break;
    case 'CA':
      $url = "http://www.site.ca";
      break;
    default:
      $url = "http://site.com";
  }

  header('Location: '.$url);
} catch (Exception $e) {
  // Handle exception
}
?>
M Ali Salim
  • 109
  • 2
  • 14
  • It's an infinite loop, cause you're redirecting them constantly to the index page, the page checks in which country they are and then redirects them to index page again. – Matheno Jun 04 '13 at 14:24

3 Answers3

1

You should check if the user is visiting the site via the localised URL before forwarding:

<?php
// Next two lines are for Beyond Hosting
// Don't forget to change your-domain
require_once '/home/your-domain/php/Net/GeoIP.php';
$geoip = Net_GeoIP::getInstance('/home/your-domain/php/Net/GeoIP.dat');

// Next two lines are for HostGator
require_once 'Net/GeoIP.php';
$geoip = Net_GeoIP::getInstance('GeoIP.dat');

try {
  $country = $geoip->lookupCountryCode($_SERVER['REMOTE_ADDR']);

  switch((string)$country) {
    case 'AU':
      $url = "http://www.site.au";
      break;
    case 'CA':
      $url = "http://www.site.ca";
      break;
    default:
      $url = "http://site.com";
  }

  if (strpos("http://$_SERVER[HTTP_HOST]", $url) === false)
  {
      header('Location: '.$url);
  }
} catch (Exception $e) {
  // Handle exception
}
?>
Stan
  • 493
  • 4
  • 15
0
use this  
header("Location:".$url);
0

can you do something like: (WARNING, i haven't tested this code, but the logic should be like this)

//Inside your try:
$country = $geoip->lookupCountryCode($_SERVER['REMOTE_ADDR']);
$serverName = explode('.', $_SERVER['SERVER_NAME']);
$serverCountryCode = $serverName[count($serverName)-1];
if (strtoupper ($serverCountryCode) != $country)) {
$shouldRedirect = true;
switch((string)$country) {
    case 'AU':
      $url = "http://www.site.au";
      break;
    case 'CA':
      $url = "http://www.site.ca";
      break;
    default:
      if ($serverCountryCode == 'com') {
        $shouldRedirect = false;
      }
      $url = "http://site.com";
  }
  if ($shouldRedirect) {
    header('Location: '.$url);
  }
}
Josejulio
  • 1,286
  • 1
  • 16
  • 30