phpsession-cookiessetcookieip2location

Set URL Same Page on IP2Location redirect


I'm going to use Redirect Visitors by Country, I use IP2LOCATION

This is my code:

require_once('vendor/geoplugin.class.php');
$geoplugin = new geoPlugin();
$geoplugin->locate();
$var_country_code = $geoplugin->countryCode;
if ($var_country_code == "IN") {
    header('Location: index.php?lang=in');
}
if ($var_country_code == "MY") {
    header('Location: index.php?lang=my');
}

I've added this above code in the head of my index.php file, the problem is the page keep refreshing continuously.

The index.php will redirect correctly to index.php?lang=in for example, but it keeps refreshing...

I've tried exit; break; meta refresh, session_start(); and other methods. I need to add session start, register the session and set the cookie, only one time that after redirect to the language by visitor country, user will be able to change language after that.

And here is my language code:

session_start();
header('Cache-control: private'); 
if(isSet($_GET['lang']))
{
    $lang = $_GET['lang'];
    // register the session and set the cookie
    $_SESSION['lang'] = $lang;
    setcookie("lang", $lang, time() + (3600 * 24 * 30));
}
else if(isSet($_SESSION['lang']))
{
    $lang = $_SESSION['lang'];
}
else if(isSet($_COOKIE['lang']))
{
    $lang = $_COOKIE['lang'];
}
else
{
    $lang = 'en';
}

How to solve this issue?

Thanks in advance


Solution

  • Store your location in a session variable and if it's already set, then the location session won't need to be refreshed again hence breaking the redirect loop. You don't need the language code.

    session_start();
    require_once('vendor/geoplugin.class.php');
    
    if(!$_SESSION['location']){
    
        $geoplugin = new geoPlugin();
        $geoplugin->locate();
        $var_country_code = $geoplugin->countryCode;
    
        $_SESSION['location'] = $var_country_code;
    
        if ($var_country_code == "IN") {
    
               header('Location: index.php?lang=in');
        }
        if ($var_country_code == "MY") {
    
                header('Location: index.php?lang=my');
        }
    
    }