James John – Software Engineer

How to Detect User’s Language Using PHP

How to Detect User’s Language Using PHP

Hi all,

I know seeing this post topic, you will think is a huge of code but looking through it well you recognise its just a pieces of codes integrated to give us what we are looking for. Here every browser has a language its browsing with, now I use PHP to call it out with the $_SERVER function

  1. <?php
  2. echo $_SERVER['HTTP_ACCEPT_LANGUAGE'];
  3. ?>

the output of that is this en-US,en;q=0.5  because am using English, now we can’t use all this to know the language i will need only the en to know its English, now what are we to do? ::)

Am going to use the substr() function to delete some letters, here it goes

  1. <?php
  2. $language = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
  3. echo $language;
  4. //you can identify a user's language using this
  5. if($language=='en')
  6. {
  7. echo"Hello user, you are English!";
  8. }
  9. ?>

The output of that code will just be en

Hope it helps! :D

James John

Software Engineer