Over a million developers have joined DZone.

Automatically Detect Browser Language With PHP

DZone's Guide to

Automatically Detect Browser Language With PHP

· Web Dev Zone
Free Resource

Try RAD Studio for FREE!  It’s the fastest way to develop cross-platform Native Apps with flexible Cloud services and broad IoT connectivity. Start Your Trial Today!

When you are working on a multinational website you may need the functionality to translate your website into different languages. There are many ways you can translate a website, in this article I will not go through the different ways you can translate a website.

But one thing is that you will always need is to know what language you want display when a user hits your page. There are different options you can do with this, either have a default language and allow the user to switch to the language they want to use, or detect the language set in the browser and switch the language automatically.

You can detect the language the browser is set to by looking at the server variable HTTP_ACCEPT_LANGUAGE.

// Detect browser language
This variable will display all the languages that you can set in your browser en-GB,en,en-US. But because you can select multiple languages for your browser they are returned as a comma separated string. From these languages you can explode the string and now you have a list of all languages that the user can read, looping through this list you can find supported languages and display these to the user.
$supportedLangs = array('en-GB', 'fr', 'de');
$languages = explode(',',$_SERVER['HTTP_ACCEPT_LANGUAGE']);
foreach($languages as $lang)
	if(in_array($lang, $supportedLangs))
                // Set the page locale to the first supported language found

Get Your Apps to Customers 5X Faster with RAD Studio. Brought to you in partnership with Embarcadero.


Published at DZone with permission of Paul Underwood, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}