Skip to content

Instantly share code, notes, and snippets.

@vroman
Created October 20, 2018 17:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vroman/4b00169fc18996db7751f677e8f7a377 to your computer and use it in GitHub Desktop.
Save vroman/4b00169fc18996db7751f677e8f7a377 to your computer and use it in GitHub Desktop.
A small function to get client-sent HTTP Accept-Language header in PHP
<?php
/*
* A small function to get client-sent HTTP Accept-Language header.
*
* Copyright (C) 2018 Víctor Román Archidona
* https://www.victorroman.es/
*
* Input:
* (int, optional): An HTTP Accept-Language header or null if it
* should be taken from $_SERVER environment.
*
* (bool, optional): Return languages sorted by preference.
*
* Demo:
* <?php
* $data = "es-es,es;q=0.8,en-us,en-en;q=0.5,en;q=0.3";
* print_r(
* getUserAcceptedLanguages($data)
* );
* ?>
*
* Output:
* Array
* (
* [0.8] => es-es,es
* [0.5] => en-us,en-en
* [0.3] => en
* )
*
* License:
* Unlicense: http://unlicense.org
*/
function getUserAcceptedLanguages($languages = null, $sorted = true)
{
if ($languages == null)
$languages = $_SERVER["HTTP_ACCEPT_LANGUAGE"];
$lang_array = array();
$lang_len = strlen($languages);
$lang_pos = 0;
while ($lang_pos < $lang_len) {
$buffer_languages = null;
$buffer_priority = null;
/* Get each language block, separated by ';' */
while ($languages[$lang_pos] != ";" && $lang_pos < $lang_len) {
$buffer_languages .= $languages[$lang_pos];
$lang_pos++;
}
/* Skips ;q= */
$lang_pos += 3;
/* Now we take the priority: */
while ($languages[$lang_pos] != "," && $lang_pos < $lang_len) {
$buffer_priority .= $languages[$lang_pos];
$lang_pos++;
}
$lang_array[$buffer_priority] = $buffer_languages;
$lang_pos++;
}
if ($sorted === true)
ksort($lang_array, SORT_REGULAR);
return $lang_array;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment