Search code examples
phphttp-redirectgeolocationgeo

Country geolocation redirects me to the wrong link?


So I have this code and my ip is from the country ph;

<?php
require_once('geoip.inc');

$gi = geoip_open('GeoIP.dat', GEOIP_MEMORY_CACHE);
$country = geoip_country_code_by_addr($gi, $_SERVER['REMOTE_ADDR']);
geoip_close($gi);

switch ($country) {
 case 'ph':
     $location = 'url/ph/index.php';
     break;
 case 'us':
     $location = 'url/intl/index.php';
     break;
 case 'in':
     $location = 'url/intl/index.php';
     break;
 default:
     $location = 'url/intl/index.php';
     break;
 }
 header('Location: '.$location.'');
 ?>  

whenever i try to access my site with that code and using my own home ip (philippines) it keeps on redirecting me on the intl/index.php page. Everything is in my home directory already like the geoip.inc and geoip.dat. Both of them are in the root folder already.

Anyone know what im missing here? Thank you!


Solution

  • Function geoip_country_code_by_addr is returning country code in upper case so PH, US, IN etc. and when you put in switch lowercase country codes always it includes default data.

    So need to change contry codes to uppercase like

    <?php
    require_once('geoip.inc');
    
    $gi = geoip_open('GeoIP.dat', GEOIP_MEMORY_CACHE);
    $country = geoip_country_code_by_addr($gi, $_SERVER['REMOTE_ADDR']);
    geoip_close($gi);
    
    switch ($country) {
     case 'PH':
         $location = 'url/ph/index.php';
         break;
     case 'US':
         $location = 'url/intl/index.php';
         break;
     case 'IN':
         $location = 'url/intl/index.php';
         break;
     default:
         $location = 'url/intl/index.php';
         break;
     }
     header('Location: '.$location.'');
     ?>