-
-
Save spham/dd4b469bd2e3d579ba0debe301110797 to your computer and use it in GitHub Desktop.
PHP: Detect Browser Language
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Get browser language, given an array of avalaible languages. | |
* | |
* @param [array] $availableLanguages Avalaible languages for the site | |
* @param [string] $default Default language for the site | |
* @return [string] Language code/prefix | |
*/ | |
function get_browser_language( $available = [], $default = 'en' ) { | |
if ( isset( $_SERVER[ 'HTTP_ACCEPT_LANGUAGE' ] ) ) { | |
$langs = explode( ',', $_SERVER['HTTP_ACCEPT_LANGUAGE'] ); | |
if ( empty( $available ) ) { | |
return $langs[ 0 ]; | |
} | |
foreach ( $langs as $lang ){ | |
$lang = substr( $lang, 0, 2 ); | |
if( in_array( $lang, $available ) ) { | |
return $lang; | |
} | |
} | |
} | |
return $default; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment