1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Geo redirect code

Discussion in 'PHP & Perl' started by Freedoom, Jun 19, 2015.

  1. Freedoom

    Freedoom Regular Member

    Joined:
    Apr 16, 2009
    Messages:
    225
    Likes Received:
    16
    Hi,

    I have this code to redirect traffic :

    Code:
    <?PHP
    include('/home/domain/public_html/geoip/geoip.inc'); //this file must exist in your directory
     
    $gi = geoip_open('/home/domain/public_html/geoip/GeoIP.dat',GEOIP_STANDARD);
     
    // get the ip of the visitor
    $addr = getenv('REMOTE_ADDR');
    // translate his ip to a country code
    $country = geoip_country_code_by_addr($gi, $addr);
    // close the geo database
    geoip_close($gi);
     
    $badcountry = array('TR','IN','ID',"PK","CN",'MY');
    // You can change the example with any countries that you want to block
     
    // redirect them if they suck
    if(in_array($country, $badcountry))
    header('Location: http://www.domain.com/'); //enter a url or page on your site
    ?>
    How can I redirect the "good" traffic(all the countries that aren't in the bad country array) to other url?

    Thanks
     
  2. fatboy

    fatboy Elite Member

    Joined:
    Aug 13, 2008
    Messages:
    1,618
    Likes Received:
    3,232
    Occupation:
    Retired
    Location:
    Old Peoples Home
    Just add an exclamation mark to the in_array line and you will only redirect the good traffic (ie: not in your bad array)

    Code:
    <?PHP
    include('/home/domain/public_html/geoip/geoip.inc'); //this file must exist in your directory
     
    $gi = geoip_open('/home/domain/public_html/geoip/GeoIP.dat',GEOIP_STANDARD);
     
    // get the ip of the visitor
    $addr = getenv('REMOTE_ADDR');
    // translate his ip to a country code
    $country = geoip_country_code_by_addr($gi, $addr);
    // close the geo database
    geoip_close($gi);
     
    $badcountry = array('TR','IN','ID',"PK","CN",'MY');
    // You can change the example with any countries that you want to block
     
    // redirect if they are not a 'bad country'
    if(!in_array($country, $badcountry))
    header('Location: http://www.domain.com/'); //enter a url or page on your site
    ?>
    

    Not tested, off the top of my head but think it should work.

    ** EDIT **

    If you want to redirect both good and bad, use this at the end:
    Code:
    if(in_array($country, $badcountry))
    {
       header('Location: http://www.domain.com/'); //enter a url or page to redirect bad traffic to
    }
    else
    {
       header('Location: http://www.domain.com/'); //enter a url or page to redirect good traffic to
    }
    
     
    Last edited: Jun 20, 2015