U
U
unlik2019-01-18 19:29:54
PHP
unlik, 2019-01-18 19:29:54

Redirect depending on the country?

How can I redirect depending on the country?
If Russia, then do not redirect, just the main page
If another page, then redirect to /en

Answer the question

In order to leave comments, you need to log in

4 answer(s)
T
ThunderCat, 2019-01-18
@ThunderCat

if the country is geoIP
if the browser language is sufficient - $_SERVER['HTTP_ACCEPT_LANGUAGE']

M
MaksPaverov, 2019-01-18
@MaksPaverov

The option is much larger than the person above, but it's working...

//Получаем IP пользователя
$ip =  $_SERVER['REMOTE_ADDR'];

//Функция whois для определения страны по IP\
function whois($ip) {
  if ($ip!="") {
    $sock = fsockopen ("whois.ripe.net",43,$errno,$errstr);
    if ($sock) {
       fputs ($sock, $ip."\r\n");
      while (!feof($sock)) {
        $str.=trim(fgets ($sock,128)." <br>");
      }
    }
    else {
          $str.="$errno($errstr)";
      return;
    }
    fclose ($sock);
  }
  return $str;
  }

//Получаем whois данные для IP пользователя
$whois =  whois($_SERVER['REMOTE_ADDR']);

//Получаем страну, исходя из whois IP
$need = "country:";
 $pos = strpos($whois,$need);
 $search = substr($whois,$pos,18);
 $excount = explode(":", $search);
 $country = trim($excount[1]);

//Ну и сам код редиректа
if($country == "US") {
header('Location: /us/');
exit();
}

D
DanKud, 2019-01-18
@DanKud

preg_match('/^\w{2}/', $_SERVER['HTTP_ACCEPT_LANGUAGE'], $m);
switch (strtolower($m[0])) {
    case 'ru': break;
    default: header('Location: /en'); break;
}

K
KirillADV, 2020-08-24
@KirillADV

I had an idea over the weekend
- you can try without cookies and unnecessary troubles
- the only question is how the search engines will react to this when indexing with the new structure and what will happen to the old links, how will the search engine process them?
Here is the structure of the site (accordingly, on each page of the site there will be the option to select the language forcibly, and the links will go, according to the structure of the site - below)
-----------------------
mydomain .ru
|
index.php (contains only the redirect (code block - 1 see below))
|
|\
mydomain.ru/eng/index.php (and all accesses to bcdct pages within the /eng/ prefix are obtained)
|
|
|\
mydomain.ru/rus/index.php (and get all accesses to bcdct pages within the /rus/ prefix)
(code block - 1)
-------------------- -------------
preg_match('/^\w{2}/', $_SERVER['HTTP_ACCEPT_LANGUAGE'], $m);
switch (strtolower($m[0])) {
case 'ru': header('Location: /rus/index.php'); break;
default: header('Location: /eng/index.php'); break;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question