Setting a Cookie with Language Preference

Learn a very basic PHP trick for setting up a cookie for a multilingual website.

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 Hebrew language version resides in the he directory.
  • The Spanish language version resides in the es directory and so on…

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 the most user-friendly. So, you do need a home page that offers links to all the language versions. That’s simple HTML, as is shown here:

Home Page Linking to the Language Versions

<a href="/en/">English</a>
<a href="/es/">español</a> 
<a href="/he/">עִברִית</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']) {
  $expire = time() + (86400*30); //30days
  setcookie('lang', $_SERVER['PHP_SELF'], $expire, '/');

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']}");

Cookies and Sessions: