0

Hey all,

I am trying to internationalise my website with php. I am very new to PHP!

The index.php starts with this:

<?php session_start(); ?>
<?php include 'api/locale.php'; ?>

<html>
  <!-- ... -->
  <div><?php loc('foo') ?></div>

The locale.php looks like this:

<?php
  if(isset($_GET['lang']) {
      $_SESSION['lang'] = $_GET['lang'];
  } else {
      $_SESSION['lang'] = 'en';     // default value
  }

  // use the necessary language file
  include('/locale/' . $_SESSION['lang'] . '.php');

  // get phrase from URL
  if (isset($_GET["phrase"]))
    loc($_GET["phrase"];);

  function loc($phrase)
  {
    global $lang;

    if(array_key_exists($phrase, $lang)) {
        echo $lang[$phrase];
    } else {
        echo $phrase;
    }
  }
?>

The idea is I want to use the function loc($phrase) to get the content either in German or English. But here is the problem:

If I have the code like this, I always get the english version, because in locale.php I can not get the lang from the URL: $_GET['lang'] is undefined. Therefore, the session language is always set to the default language (en).

However, if I move the session_start(); into the file locale.php, the internationalisation works:

index.php:

<?php include 'api/locale.php'; ?>

<html>
  <!-- ... -->
  <div><?php loc('foo') ?></div>

locale.php:

<?php
  session_start();
  if(isset($_GET['lang']) {
      $_SESSION['lang'] = $_GET['lang'];
  // ... rest the same as above

Why is it like this? Am I doing something conceptually wrong? The problem is I am also using this locale.php in ajax calls to get international content for dynamically generated HTML elements:

function loc(phrase)
{
  var locString;
  $.ajax({
    // force synchronous ajax call, to return with locString
    async: false,
    // url with to be translated id
    url: "api/locale.php?phrase=" + phrase,
    // "get" for small data (otherwise post)
    method: "get",
    // callback function after server has reveiced information
    success: function (data)
      {
        locString = data;
      }
  });
  return locString;
}

So if I call locale.php over and over again with this AJAX call, aren't there new sessions starting over and over again? I am not sure if I designed my functions correctly. I am happy about any comments!

Thank you!

=============== EDIT ===============

ok, I tried a new way now:

  1. session.php

    // session starts at this point
    session_start();
    
    // internationalisation in EN and DE
    $allowedLangs = array('en', 'de');
    
    // check lang-parameter given in URL and set language from there
    if(isset($_GET['lang']) && in_array($_GET['lang'], $allowedLangs))
      $_SESSION['lang'] = $_GET['lang'];
    
    if(!isset($_SESSION['lang']))
      $_SESSION['lang'] = 'en';     // default value
    
  2. locale.php

    // include correct languguage file
    $root = realpath($_SERVER["DOCUMENT_ROOT"]) ;
    include($root . '/locale/' . $_SESSION['lang'] . '.php');
    
    // get phrase from URL and translate it
    if (isset($_GET["phrase"]))
    {
      $phrase = $_GET["phrase"];
      global $lang;
    
      if (array_key_exists($phrase, $lang))
        echo $lang[$phrase];
      else
        echo $phrase;
    }
    

both files get included in index.php

<?php include 'api/session.php'; ?>
<?php include 'api/locale.php'; ?>

However, if I locale a phrase with ajax now, the following error message appears:

Notice: Undefined variable: _SESSION in ... /locale.php on line 4

How can that be? I thought $_SESSION is superglobal ?!?

1
  • You should still be able to access $_GET in included and required files...
    – Ry-
    Apr 20, 2013 at 22:33

3 Answers 3

2

When you call the version of api/locale.php with the session_start via ajax, not a new but the same session will start, which is the correct behaviour.

Word start maybe confusing you but the session start will supply the information of the current session correctly, not a new one. So nothing to worry about.

Also you may consider looking at

$_SERVER['HTTP_ACCEPT_LANGUAGE']

before starting to ajax ping-pong of the server and client for an initial language quick guess...

For the two versions of your code, it is not a mystery why it works when session_start is
in locale.php.

The cause is:

Your ajax call is not entering your script from index.php, it enters directly to api/locale.php.

If you do not session_start in api/locale.php, the ajax call will enter into a sessionless php invocation.

So it will keep the default value since session data is neither can be fetched or can be recorded.

1
  • oooh, interesting! Thank you for the clarification :) Apr 29, 2013 at 13:00
1

I think there is something conceptually wrong in your locale.php file. The fact that you always set $_SESSION['lang'] is a bad smell.
There should be a case when you dont set the value of $_SESSION['lang']and just use the value of$_SESSION['lang']without modifying it.
With your locale file as it is , and your ajax call that does not pass 'lang' as a parameter, you will always get the default language.
But anyway your local.php file should start with session_start(); as explained by ishan.

By the way you should not use 'echo' inside your function loc. Instead return the result and do

echo loc('foo');

It would do the same job, but your loc function would be more reusable.

2
  • +1 You have a good point there... Why set language at every access? And I missed it :).
    – Volkan
    Apr 21, 2013 at 10:54
  • And again: Thank you for your clarification as well. As I said, I am really new to server-side coding and php. Of course it seems weird to set the $_SESSION['lang'] everytime. But somehow I could not find another way to set the superglobal variable beforehand and always access it in this locale.php files. Any ideas? Another global php file that starts the session and sets all the superglobal variables? Apr 29, 2013 at 13:04
0

Hi Marcus I will try to answer your question in the comments.

$_SESSION id indeed a super global. But you need to call session_start() for it to works. That's why it does not work anymore in locale.php

The problem is that your locale.php file is serving two purposes at the same time. It should just translate but not be reachable directly from an url. So you should do something like this :

  1. session.php
    `

    //here you define a default value. So whatever happens, you know that $_session['lang']
    //will always be set.

    if(! isset ($_SESSION['lang'] {
       $_SESSION['lang'] = 'en';     // default value
    }
    
    // internationalisation in EN and DE
    $allowedLangs = array('en', 'de');
    
    // check lang-parameter given in URL and set language from there
    //if necessary, the default value will be overwritten.
    if(isset($_GET['lang']) && in_array($_GET['lang'], $allowedLangs)) {
      $_SESSION['lang'] = $_GET['lang'];
    }
    
  2. `translate.php

    function getTranslation ($phrase, $lang='en') {

     $root = realpath($_SERVER["DOCUMENT_ROOT"]) ;
     include($root . '/locale/' . $lang . '.php');
    
     //the array with the phrases and their translations should not be called $lang 
     //to avoid confusion. Let's call it $translations
     if (array_key_exists($phrase, $translations))
       return $translations[$phrase];
     else
       return $phrase;
     }
    

    }

  3. locale.php ` This file is to be called in ajax. It will works providing $_SESSION['lang'] as already been defined (in index.php for example). Otherwise you fall back to the default lang.

    include 'path_to_translate/translate.php';

    session_start();

    if(isset($_SESSION['lang'] {
    $lang = $_SESSION['lang'];
    } else {
    $lang = 'en';
    }

    $phrase = $_GET['phrase'];

    echo getTranslation($phrase, $lang);

  4. index.php

       session_start(); 
       include 'api/session.php'; 
       include 'path_to_translate/translate.php';
    
       $lang = $_SESSION['lang'];
    
    
    
    <some html>
    
    //to translate anything
    <?php echo getTranslation($anything, $lang)  ?>  
    
    </some html> 
    

Hope this will help. Off course I can not test all this code , so their might be some mistake. But that's the general idea.
I tried not to change to much what you' have done. But there is still a problem. You should not define the lang in index.php. If there is a form in your index to choose the lang. Make a call in ajax to set_lang.php. It is not for the index to set the lang in session.

3
  • Sorry for the code above, I can not format it properly. I do not know why. Apr 29, 2013 at 17:07
  • thank you so much for your code. I will try to use it and then tell you if I succeeded :) Apr 30, 2013 at 19:37
  • thank you for some of the php coding tricks. The majority of it works. However, with your code I do not see a way how to set the language of a text node that is dynamically appended with JavaScript. So, what do I do if I want to fill an HTML node with text: $('#someId').html(???) Apr 30, 2013 at 19:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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