I'm bulding a multilanguage web in PHP, i have the class for the language change, i can do it by setting the $_SESSION or just by changing the lang value in the url, i'm working with rewrite mod for apache so this is how my URL looks like:

I have a function that displays an upper bar in the entire site, and in that bar i have the flags for language change.

I use this class to change Language:

class IDIOMAS {

    private $UserLng;
    private $langSelected;
    public $lang = array();

    public function __construct($userLanguage){

        $this->UserLng = $userLanguage; 

    public function userLanguage(){


            case "en":
                $lang['PAGE_TITLE'] = TITULO().' | Breaking news, World news, Opinion';

                // Menu

                $lang['MENU_LOGIN'] = 'Login';
                $lang['MENU_SIGNUP'] = 'Sign up';
                $lang['MENU_LOGOUT'] = 'Logout';
                $lang['MENU_SEARCH'] = 'Search';

                $lang['SUBSCRIBE_SUCCESS'] = "¡Thank you, we'll let you know when we become online!";
                $lang['SUBSCRIBE_EMAIL_REGISTERED'] = 'This e-mail is already registered';
                $lang['SUBSCRIBE_EMAIL_INVALID'] = 'The e-mail you entered is invalid';
                $lang['SUBSCRIBE_EMAIL_WRITE'] = 'You must write down your e-mail';
                $lang['SUBSCRIBE_TITLE'] = '¡Subscribe!';
                $lang['SUBSCRIBE_CONTENT'] = 'And be the first to read the best articles in the web';
                $lang['SUBSCRIBE_PLACEHOLDER'] = 'Enter your E-mail';
                $lang['SUBSCRIBE_SEND'] = 'SEND';

                $lang['LOGIN_TITLE'] = 'Please Login to your account';
                $lang['LOGIN_USER'] = 'User';
                $lang['LOGIN_PASSWORD'] = 'Password';
                $lang['LOGIN_ERROR'] = '¡User and/or password invalid!';

                $lang['REGISTER_NAME'] = 'Please write your name';
                $lang['REGISTER_LAST_NAME'] = 'Please write your last name';
                $lang['REGISTER_EMAIL'] = 'Write your E-mail';
                $lang['REGISTER_CITY'] = 'Enter your City name';
                $lang['REGISTER_COUNTRY'] = '¿Where are you from?';
                $lang['REGISTER_ZIP_CODE'] = 'Enter your ZIP Code';
                $lang['REGISTER_DATE_BIRTH'] = 'Please enter your date of birth';

                return $lang;

            case "es":
                $lang['PAGE_TITLE'] = TITULO().' | Noticias de última hora, Noticias mundiales, Matrices de opinión';

                // Menu

                $lang['MENU_LOGIN'] = 'Entrar';
                $lang['MENU_SIGNUP'] = 'Registrarse';
                $lang['MENU_LOGOUT'] = 'Salir';
                $lang['MENU_SEARCH'] = 'Buscar';

                $lang['SUBSCRIBE_SUCCESS'] = "¡Gracias, te avisaremos cuando estemos online!";
                $lang['SUBSCRIBE_EMAIL_REGISTERED'] = 'Este email ya se encuentra registrado';
                $lang['SUBSCRIBE_EMAIL_INVALID'] = 'El correo que introdujiste es inválido';
                $lang['SUBSCRIBE_EMAIL_WRITE'] = 'Debes escribir tu email';
                $lang['SUBSCRIBE_TITLE'] = '¡Suscríbete!';
                $lang['SUBSCRIBE_CONTENT'] = 'Y se el primero en leer las mejores noticias y artículos en la web';
                $lang['SUBSCRIBE_PLACEHOLDER'] = 'Introduce tu E-mail';
                $lang['SUBSCRIBE_SEND'] = 'Enviar';

                $lang['LOGIN_TITLE'] = 'Por favor inicia sesión en tu cuenta';
                $lang['LOGIN_USER'] = 'Usuario';
                $lang['LOGIN_PASSWORD'] = 'Clave';
                $lang['LOGIN_ERROR'] = '¡Usuario y/o clave incorrectos!';

                $lang['REGISTRO_NOMBRE'] = 'Por favor introduce tu nombre';
                $lang['REGISTRO_APELLIDO'] = 'Por favor introduce tu apellido';
                $lang['REGISTRO_CORREO'] = 'Introduce tu correo electrónico';
                $lang['REGISTRO_CIUDAD'] = 'Introduce el nombre de tu ciudad';
                $lang['REGISTRO_PAIS'] = '¿De donde eres?';
                $lang['REGISTRO_CODIGO_POSTAL'] = 'Introduce tu Código Postal';
                $lang['REGISTRO_FECHA_NAC'] = 'Por favor introduce tu fecha de nacimiento';

                return $lang;


I use this class with this code:

$language = new IDIOMAS($lang);
$langArray = array();
$langArray =  $language->userLanguage();

And set the language like this:

if (!isset($_SESSION['idioma'])){
    $lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
    $_SESSION['idioma'] = $lang;
    $lang = $_SESSION['idioma'];

if(isset($_GET['lang']) && in_array($_GET['lang'], array('en', 'es'))){
    $_SESSION['idioma'] = $_GET['lang'];
    $lang = $_SESSION['idioma'];

Now the issue i have is that when i try to change language of the page i'm on, i mean, if i'm located in and nothing else i need to put the /es or /en at the end for changing the lang, but if i'm in i need to change specificallly the /es parameter.

I have a function to get the current url for redirections when being logged or register.

function getUrl() {
  $url  = @( $_SERVER["HTTPS"] != 'on' ) ? 'http://'.$_SERVER["SERVER_NAME"] :  'https://'.$_SERVER["SERVER_NAME"];
  $url .= $_SERVER["REQUEST_URI"];
  return $url;

I was trying to change the lang value inside that function with no success,

Really appreciate any help



这是一个简单的解决方案,我会这样做。 我不知道它是否正是你想要使用的:</ p>

$ pos1 = strpos($ url,'/ “); //整个URL
$ pos2 = strpos($ url, '/',$ POS1); //现在通过偏移

$ base = substr($ url,0,$ pos1)找到第二个; //获取域名half
$ end = substr($ url,$ pos2); //获取语言区域之后的所有内容

$ val = $ base。'/'。$ newlang。'/'。$ end;
return $ val;
</ code> </ pre>

您可能需要在$ pos上添加或减去1才能获得正确的值,如下所示:</ p>

  $ pos2 = strpos($ url,'/',$ pos1 + 1);  //如果找到错误的斜杠
$ base = substr($ url,0,$ pos1-1); //如果它返回斜杠
$ end = substr($ url,$ pos2 + 1); //如果它返回斜杠
</ code> </ pre>

请调整并测试它,它只是操作中的概念,我还没有测试过这个剪辑。</ p>
</ div>



Here is a simple solution that I would do. I don't know if its exactly what you'll want to use:

 // Find the first forward slash location
 $pos1 = strpos($url,'/'); // The whole URL
 // You only need this next line if your language codes are different sizes
 // If they are always 2 then can alter the code to not use it
 $pos2 = strpos($url,'/',$pos1); // Now find the second by offsetting

 $base = substr($url,0,$pos1); // Get domain name half
 $end = substr($url,$pos2); // Get everything after language area

 // Now from the function return the result
 $val = $base.'/'.$newlang.'/'.$end;
 return $val;

You may need to add or subtract 1 on the $pos to get the right values returned, like so:

 $pos2 = strpos($url,'/',$pos1+1); // In case its finding the wrong slash
 $base = substr($url,0,$pos1-1); // In case its returning the slash
 $end = substr($url,$pos2+1); // In case its return the slash

Please tweak and test this, it is only the concept in action, I have not tested this snip-it.

dso407787736 谢谢回答! strpos对我不起作用,因为函数getUrl()返回包含http://的整个url,这使得strpos返回错误/位置
大约 6 年之前 回复

最后我通过修改getUrl函数得到它:</ p>

  function getUrl  ($ newlang){
$ url = @($ _SERVER [“HTTPS”]!='on')? 'http://'。$_SERVER [“SERVER_NAME”]:'https://'。$_SERVER [“SERVER_NAME”];
$ url。= $ _SERVER [“REQUEST_URI”];
$ substr = substr ($ url,27,3);
$ base = substr($ url,0,28);
$ resto = substr($ url,31,1000);
$ newUrl = $ base。$ newlang。 “/".$resto;
返回$ newUrl;
</ code> </ pre>

并调用此函数,如getUrl(”en“)或getUrl(”es “); </ p>

这可能对其他人有用。</ p>
</ div>



Finally i got it by modifying the getUrl function to this:

function getUrl($newlang) {
    $url  = @( $_SERVER["HTTPS"] != 'on' ) ? 'http://'.$_SERVER["SERVER_NAME"] :  'https://'.$_SERVER["SERVER_NAME"];
    $url .= $_SERVER["REQUEST_URI"];
    $substr = substr($url,27,3);
    $base = substr($url,0,28);
    $resto = substr($url,31,1000);
    $newUrl = $base.$newlang."/".$resto;
    return $newUrl;

and calling the function like this getUrl("en") or getUrl("es");

Maybe this can be usefull for someone else.

Csdn user default icon