Saving the User's Language Preference

setcookie('lang', $_SERVER['PHP_SELF'], time() + 30*24*60*60, '/')

Many web pages are multilingual. In addition, they are often organized so that every localized section resides in its own directory, similar to this approach:

  • The English language version resides in the en directory.

  • The Spanish language version resides in the es directory.

  • The French language version resides in the fr directory.

You can detect the language of the user in several different ways:

  • By trying to tie the client's IP address to a geographical region

  • By reading the Accept-Language HTTP header to determine which languages are the preferred ones

  • By asking the user

Although all of these methods work somehow, the final one (or a combination of several of them) is considered to be most user-friendly. So, you do need a home page that offers links to all three versions. That's simple HTML, as is shown here:

Home Page Linking to the Various Language Versions
<a href="en/index.php">English version</a><br />
<a href="es/index.php">Versión español</a><br />
<a href="fr/index.php">Versione française</a>

Now, every language directory has an index.php file in the specific language. In this file, the code is included from the listing at the beginning of This. This checks whether there is already a language cookie. If not, it tries to set a cookie with the current path (retrieved from $_SERVER['PHP_SELF']).

Saving the Current Path in a Cookie
  if (!isset($_COOKIE['lang']) ||
    $_COOKIE['lang'] != $_SERVER['PHP_SELF']) {
    setcookie('lang', $_SERVER['PHP_SELF'],
      time() + 30*24*60*60, '/');

It is important to set the cookie's path to the root directory of the web server. Otherwise, the path defaults to the current path and the cookie is automatically only readable in the current directory and its subdirectories, and not on the home page.

Finally, you have to check on the home page to determine whether the cookie is present, and, if so, redirect the user to the appropriate page. To do so, the following code must be added at the top of the multilingual.php page.

  if (isset($_COOKIE['lang']) && $_COOKIE['lang'] !=
   '') {
    header("Location: {$_COOKIE['lang']}");