地理重定向用户只是一次使用php


Geo redirect user just once using php

当用户登陆site.com/redirect.php时,我可以很容易地使用这个脚本他们会根据地理IP被重定向到合适的TLD但是当我在'index.php'中添加这段代码时,它会创建一个重定向循环。你能帮我修改一下,这样它就不会产生循环了吗?现在这个"休息"没有帮助…

<?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
}
?>

您应该检查用户是否通过本地化URL访问网站,然后再转发:

<?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
}
?>
use this  
header("Location:".$url);

你可以这样做:(警告,我还没有测试过这段代码,但逻辑应该是这样的)

//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);
  }
}