Detect Browser Language in PHP

Detect Browser Language in PHP

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

Stefan Bogdanescu

Founder & Senior Architect

Detect Browser Language in PHP

Your current implementation attempts to parse the HTTP_ACCEPT_LANGUAGE header and fall back to the User-Agent string when the primary parsing fails. While this is a common pattern, the logic relies heavily on fragile string matching against a hardcoded list of languages. The specific failure you are experiencing—where the script defaults to English despite detecting another language—is almost certainly caused by how modern browsers format the Accept-Language header versus what your regex and substring checks expect.

The header value is not just a comma-separated list like en,fr;q=0.9. It often includes quality values (the q= parameter) and region codes immediately following the language tag, such as en-US,en;q=0.9. Your current loop checks if the global string starts with a specific code (strpos($_AL, $K)===0). This works for en but breaks down when checking for fr in en-US,en;q=0.9, because fr does not appear at the start of that string. Furthermore, falling back to User-Agent parsing is a significant source of noise, as browser strings are versioned and inconsistent across operating systems.

Parsing the Accept-Language Header Correctly

To fix this robustly, you must parse the header values sequentially rather than searching for substrings globally. The standard approach involves splitting the header string by commas and then evaluating each segment to find the first one that contains a language code from your supported list.

Here is a refined function that handles the quality values and region codes correctly:

function detect_lang_from_accept_language(array $supported_languages, string $header_value = ''): string
{
    if (empty($header_value)) {
        return '';
    }

    // Split by comma to handle multiple preferences
    $preferences = explode(',', $header_value);

    foreach ($preferences as $preference) {
        // Clean up whitespace and trim
        $preference = trim($preference);
        
        // Skip if empty
        if (empty($preference)) {
            continue;
        }

        // Extract the language code part. It usually appears before ';' or ','
        // Example: "en-US" or "fr;q=0.8"
        $language_part = explode(';', $preference)[0];
        $language_part = trim($language_part);

        foreach ($supported_languages as $lang) {
            // Check if the supported language is contained in the preference string
            // This handles both "en", "en-US", and "fr-FR" for a target of "fr"
            if (stripos($language_part, $lang) !== false) {
                return $lang;
            }
        }
    }

    return '';
}

This approach iterates through the user's preferences in order of priority. It extracts the base language tag from each preference string and checks against your $GLOBALS['_LANG'] array using stripos. This ensures that even if a user sends de-DE,de;q=0.9, you correctly identify de as the primary match before checking secondary options.

Handling Fallbacks and Defaults

If the header parsing yields no result (which is rare but possible), falling back to the User-Agent string is a valid strategy, provided you are careful about what you extract. Instead of running complex regex patterns that might accidentally match English words in non-English strings, look for common browser identifiers or known language codes explicitly mentioned in the UA string.

function detect_lang_from_user_agent(string $user_agent): ?string
{
    if (empty($user_agent)) {
        return null;
    }

    $ua_lower = strtolower($user_agent);

    // A more robust check for specific language indicators
    $detections = [
        'ru' => '/\brussian\b|[\(\[]ru[\)\]]/i',
        'de' => '/german|deutsch/i',
        'fr' => '/french|français/i',
        'es' => '/spanish|español/i',
        'it' => '/italian|i taliano/i',
        // Avoid generic matches that might cause false positives
    ];

    foreach ($detections as $lang => $pattern) {
        if (preg_match($pattern, $ua_lower)) {
            return $lang;
        }
    }

    return null;
}

In your lixlpixel_detect_lang function, update the logic to call this parser only after exhausting the Accept-Language header. If both sources fail, return your default language (en) as defined in $GLOBALS['_DLANG'].

Integration and Trade-offs

When integrating this into your existing switch statement, ensure that you are not relying on session variables for language detection unless a user has explicitly chosen one. Session-based language preference is a separate concern from automatic browser detection. Mixing them can lead to confusion where a returning user's detected browser language overrides their saved preference.

The primary trade-off here is performance versus accuracy. Parsing the header is fast, but maintaining an exhaustive list of every possible language code and region variant can be tedious. If you are using a framework like Laravel, consider leveraging its localization helpers which handle these string manipulations internally, reducing the risk of implementation errors found in custom index scripts.

For complex multi-lingual projects, this header-based detection is often just the entry point. A more robust architecture might involve a database-driven language map or a dedicated middleware that normalizes the detected code into an internal locale format (e.g., converting en to en_US) before loading views. This prevents issues where a user accepts zh-Hans but your application only serves zh, potentially returning broken content if the fallback isn't handled perfectly.

Our network