Using the PHP HTTP_ACCEPT_LANGUAGE server variable

Using the PHP HTTP_ACCEPT_LANGUAGE server variable

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

The Hidden Trap in Parsing HTTP_ACCEPT_LANGUAGE

You are likely relying on the HTTP_ACCEPT_LANGUAGE header to determine a user's preferred language, assuming that a string like es-419 or es-CO will simply resolve to "Spanish." This logic fails when regional variants exist. If your application loads in English for users in Colombia despite their browser settings indicating Spanish, the issue lies in how you are parsing the RFC 7231 header value.

The header does not contain a single language code; it contains a comma-separated list of preferences sorted by quality values (q-values). Your current implementation extracts only the first two characters:

$http_lang = substr($_SERVER["HTTP_ACCEPT_LANGUAGE"], 0, 2);
switch ($http_lang) {
    case 'en':
        $SESSION->conf['language'] = 'english';
        break;
    case 'es':
        $SESSION->conf['language'] = 'spanish';
        break;
    default:
        // Fallback logic
}

This approach works for generic locales like en-US (extracting en) or fr-CA (extracting fr). However, it breaks down with specific regional codes that include non-letter characters. The source material notes that the Locale Identifier (LCID) for Spanish(Colombia) is often represented as es-CO. While browsers typically normalize this to a standard BCP 47 tag like es-419 or es-CO, your code assumes the string starts with exactly two alphabetic characters.

The critical failure point occurs when the header value includes a region code that is not a single letter, such as es-419 (Latin American Spanish) or es-CO. Your substr call grabs es, which matches your case statement. However, if the user's browser sends es-ES, es-AR;q=0.8 (Spain first, Argentina second), and you only look at the first two characters of the first option, you might miss nuances if the logic doesn't account for quality values properly.

More commonly, the issue arises when the header is formatted with a region code that contains digits or specific scripts, though standard browsers usually output es-419. If your system expects a 2-letter ISO code but receives es-419, your switch statement might inadvertently match es correctly, but if you strip everything else, you lose the ability to serve localized content (e.g., Colombia-specific currency or formatting) even though the language is correct.

The real problem described in the source material—that Colombian users see English—usually stems from a mismatch between the browser's sent value and your fallback mechanism. If the header is es-419, your code sets it to Spanish. However, if the browser sends en-US; q=0.8, es-419; q=0.5 (common in some older configurations or proxy setups), your code grabs en. You are ignoring the quality factor entirely.

To fix this, you must parse the header according to RFC 7231. You need to:

  1. Split the string by commas.
  2. Iterate through each segment to find the one with the highest q value (defaulting to 1 if absent).
  3. Extract only the language tag part before any hyphen or semicolon.

Here is a robust implementation pattern:

function getPreferredLanguage($acceptHeader) {
    // Default fallback
    $lang = 'english'; 
    
    if (!empty($acceptHeader)) {
        $langs = preg_split('/ *, */', $acceptHeader);
        
        foreach ($langs as $segment) {
            // Remove quality parameter (e.g., "es-419; q=0.8")
            $cleanSegment = preg_replace('/;.*$/', '', trim($segment));
            
            // Extract language code (stops at hyphen or end of string)
            $parts = explode('-', $cleanSegment, 2);
            $code = $parts[0];
            
            // Check for 'en' or 'es' based on the source logic
            if (in_array($code, ['en', 'es'])) {
                return $code;
            }
        }
    }

    return $lang;
}

// Usage
$http_lang = getPreferredLanguage($_SERVER["HTTP_ACCEPT_LANGUAGE"]);

switch ($http_lang) {
    case 'en':
        $SESSION->conf['language'] = 'english';
        break;
    case 'es':
        $SESSION->conf['language'] = 'spanish';
        break;
    default:
        // Handle unknown languages via prefs
        $SESSION->conf['language'] = $PREFS->conf['languages'][$SESSION->conf['language_id']];
}

This approach ensures that if a user sends en-US, you get en. If they send es-419, you get es. It also handles cases where multiple languages are listed by respecting the quality factor, ensuring you don't accidentally default to English because it appeared first with a low priority.

If your application requires more granular control, such as distinguishing between es-ES (Spain) and es-419 (Latin America), you should store the full BCP 47 tag rather than just the ISO 639-1 language code. This allows you to map specific regions to localized assets without relying solely on a generic en fallback.

Our network