0

I have a multi-language Joomla 3.4 that at the moment only has 2 languages:

  1. my-domain.com/en/
  2. my-domain.com/es/

I want to redirect the visitor to EN/ES according to their IP (with this library).

I put my redirect code in the /templates/my-template/index.php file. This is my code:

if ( !isset($_SESSION["client_country"]) ) {
    $_SESSION["client_country"] = getCountryFromIP($_SERVER["REMOTE_ADDR"]);
    $client_country = $_SESSION["client_country"];
    $_SESSION["total_redirections"] = 1;

    if ( ($client_country == "EN") || ($client_country == "UK") ) {
        header('Location: http://www.my-domain.com/en/');
    }
    else {
        header('Location: http://www.my-domain.com/es/');
    }
}
else {
    $_SESSION["total_redirections"] ++;
    $client_country = $_SESSION["client_country"];

    if ( $_SESSION["total_redirections"] <= 2 ) {
        if ( ($client_country == "EN") || ($client_country == "UK") ) {
            header('Location: http://www.my-domain.com/en/');
        }
        else {
            header('Location: http://www.my-domain.com/es/');
        }
    }
}

The problem:

  • My first and second visits: I am correctly redirected to EN/ES according to my IP.
  • My third and subsequent visits: I am no longer redirected to EN/ES according to my IP (I'm redirected to the website's default
    language).

How do I fix this?

Thank you!

2
  • Redirecting the users to the language you believe they will want based on their IP is a bad UX idea.
    – FFrewin
    May 13, 2017 at 15:54
  • As I know, Joomla redirects automatically to the browser's language settings. I see this at my multilanguage site (6 languages) which indeed is a good idea, if you're travelling around the world aso. Once you've changed language, it keeps the language b/c this is stored via cookie. May 13, 2017 at 16:41

3 Answers 3

1

Just to re-iterate on what @FFrewin said in the comments, this is a very bad idea and should not be done via IP. I'm British and I lived in Spain for a few years, but this doesn't mean I wanted websites to be automatically displayed to me in Spanish.

As for the session, I'd suggest using Joomla's JSession API rather ths PHP native $_SESSION and you should be using a system plugin for this, not pushing the code into the template.

Firstly, have a lok at this: https://docs.joomla.org/J3.x:Creating_a_Plugin_for_Joomla

Then for the actual plugin code, you'll want to use something like the following:

<?php

defined( '_JEXEC' ) or die;

class plgSystemSOMETHING extends JPlugin
{
    protected $autoloadLanguage = true;

    public function onBeforeRender()
    {
        include 'path/to/geoiploc.php';

        $address = JFactory::getApplication();
        $session = JFactory::getSession();
        $country = $session->get('client_country');

        if (!isset($country))
        {
            $session->set('client_country', getCountryFromIP($app->input->server->get('REMOTE_ADDR')));
            $session->set('total_redirections', 1);

            $country = $session->get('client_country');

            if ($country == 'EN' || $country == 'UK')
            {
                $app->redirect(JRoute::_('http://www.my-domain.com/en'));
            }
            else
            {
                $app->redirect(JRoute::_('http://www.my-domain.com/es'));
            }
        }
        else
        {
            $total = $session->get('total_redirections');
            $total ++;

            if ($total <= 2 )
            {
                if ($country == 'EN' || $country == 'UK')
                {
                    $app->redirect(JRoute::_('http://www.my-domain.com/en'));
                }
                else
                {
                    $app->redirect(JRoute::_('http://www.my-domain.com/es'));
                }
            }
        }
    }
}

Code is untested so may need tweaking.

0

Redirecting the users to the language you believe they will want based on their IP is a bad UX idea.

However, regarding why your code might be stopping after your 2nd visit, likely it is related to the fact that you set $_SESSION['total_redirections']=1; which you are increasing it with $_SESSION['total_redirections']++; and then you do whatever you do with this condition: if ( $_SESSION["total_redirections"] <= 2 ).

So, the $_SESSION["client_country"] likely is already set, so you run at your else where the $_SESSION["total_redirections"] is >2 after your 2 visits, so there is nothing left more in your code to be done.

But again, even if you fix your code and make it work the way you like, reconsider the idea of doing this re-direction on behalf of your users.

5
  • 1) I assume the risk of detecting the client's country through its IP. 2) Obviously if $ _SESSION ["total_redirections"] is> 2 the code does not do anything, and therefore there is no more redirection. That's just my problem! 3) I can not put: if ($ _SESSION ["total_redirections"] <= 15) because there are many redirects! 4) How do I redirect without falling into an infinite loop of redirects? 5) Any help is welcome! Very very thanks! May 13, 2017 at 16:44
  • @GeorgeBerkeley I don't speak Spanish(??) - and this site is for english only.
    – FFrewin
    May 13, 2017 at 16:48
  • Sorry. I edited it. May 13, 2017 at 16:50
  • @GeorgeBerkeley - sorry I don't know how overall your code behaves on a real case, not sure about the infinite loops of redirections - (have you encountered them??), nor I am actually very clear on what you call visits and how you perform/count them. Q: when you first visit and it takes you to the language you expect - if you keep going, does the site stays on that language or it switches after 2 more page views? What I suspect is that your sessions keeps for some time and after it has reach your total redirections your code stops working - but I am not sure what you do and you fill it up...
    – FFrewin
    May 13, 2017 at 17:16
  • @GeorgeBerkeley: As for the other part regarding the bad idea of doing this - I didn't mention anything about the risks of detecting the visitor's country, this is the least. But even there was a 100% accurate way, this is a bad User experience practice from the user's point - because what happens if I am visiting from Spain but I don't speak spanish and want to reach the ENG version of the site? There are way better ways to deal with this and you should let your users free to choice. Apart of this, your implementation is hacky. Am I able to switch lang after the site takes me to ENG ???
    – FFrewin
    May 13, 2017 at 17:26
0

I found a solution to Redirect the user by his browser language. This is my code:

<?php
  $url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
  $lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
  $path = parse_url($url, PHP_URL_PATH);
  $pathFragments = explode('/', $path);
  $end = end($pathFragments);
  if ($lang == "de") {
      header("Location: https://example.com/de/{$end}");
  }
?>

I hope this helps if someone needs it. Greets, Magnus

2
  • It is nicer for future researchers if the bulk of your answer is written out here. Link-only answers are not encouraged on StackExchange sites.
    – mickmackusa
    Aug 3, 2018 at 4:34
  • @mickmackusa I edited the answer now its showing my solution
    – M.Singer
    Aug 3, 2018 at 6:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.