Category: PHP

Detect languages with PHP

If you have a standard website with CMS such Drupal, WordPress, phpBB… You may want to detect language in some pages.
To do so, you can use the following PHP function :

$_SERVER['HTTP_ACCEPT_LANGUAGE']

You should create an array of all the accepted languages, for example let’s say it’s French, English, Portuguese and Russian :

$acceptLang = ['fr', 'en', 'pt', 'ru'];

Then, you can set a default language, usually English the universal language, and detect if it’s in the array. Which will give:

$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
$acceptLang = ['fr', 'en', 'pt', 'ru'];
$lang = in_array($lang, $acceptLang) ? $lang : 'en';

Finally, in your code, you can use the value of the $lang variable to change the value of your text according the the selected language.

Inline function javascript to put cookies without JQuery

If you are using basic pages such landing pages, is it possible that you still use basic languages such HTML/CSS/Javascript.
Here is an example of putting cookies and a log of the cookies with an inline function:

<a style="cursor: pointer;" onclick='(function() {
  document.cookie = "cookie=value"; 
  console.log( "cookies:", document.cookie ); 
})()'>
  Click Me 
</a>

Because we are not using href but onlick, I added the cursor style of pointer so the user can know he can click.