Question

I'm trying to add some code to my website, in order to redirect users depending on their IP address. Whatever I do I'm getting a "This webpage has a redirect loop" message.

Here's my code:

if(isset($_GET['FirstTimer'])){
    setcookie('FirstTimer','something',strtotime('+1 year'),'/');
    $_COOKIE['FirstTimer']='something'; 
}

require_once('geoip.inc');

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

if(!isset($_COOKIE['FirstTimer'])): 
    if($_SERVER['REQUEST_URI'] == '/'){ 
        switch((string)$country) {
            case 'GR':
                header('Location: http://mywebsite.com/');
                break;
            case 'RU':
                header('Location: http://mywebsite.com/ru');
                break;
            default:
                header('Location: http://mywebsite.com/en');
        }
    }
endif;

geoip_close($gi);

The "FirstTimer" cookie is used to determine whether the visitor is a new one or not (because I'd like to redirect new visitors only).

The code is placed on the top of my index.php file, and there are no spaces before '\<\?php ?>' tags.

Was it helpful?

Solution

I am assuming that $_GET['FirstTimer'] is not set. So your switch is always executed.

When geoip returns GR your script will redirect to http://mywebsite.com/ again. $_SERVER['REQUEST_URI'] returns / and you are back in your switch again.

There is your loop.

EDIT

I've changed your script a little bit. Instead of logging if the user visits the first time, which makes no sense, just log when the user visited the last time. If this cookie is not set, start geoip and redirect the user. If it is set, update the time.

if(!isset($_COOKIE['last_visit'])) {
    setcookie('last_visit',date("Y-m-d H:i:s"),strtotime('+1 year'),'/');

    require_once('geoip.inc');

    $gi = geoip_open('GeoIP.dat', GEOIP_MEMORY_CACHE);
    $country = geoip_country_code_by_addr($gi, $_SERVER['REMOTE_ADDR']);
    if($_SERVER['REQUEST_URI'] == '/'){ 
        switch((string)$country) {
            case 'GR':
                header('Location: http://mywebsite.com/');
                break;
            case 'RU':
                header('Location: http://mywebsite.com/ru');
                break;
            default:
                header('Location: http://mywebsite.com/en');
        }
    }

    geoip_close($gi);
} else {
    setcookie('last_visit',date("Y-m-d H:i:s"),strtotime('+1 year'),'/');
}

But you should definitely enhance this script because what happens, if you have a user that gets on your page with this: http://yourwebsite.com/great/article/link.html. Perhaps you do have a translation for this, but the user won't be redirected.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top