-
-
Save dimayakovlev/c5d4c5c675fdc8c52aa935062ec58be8 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 empty( $langs ) ? $default : $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