Detect Browser Language in PHP: A Robust Solution
The provided PHP script encounters challenges in accurately detecting browser languages, often defaulting to "index_en.php" for all languages. To address this issue, a more comprehensive approach is required.
One robust solution is to utilize built-in PHP functions and a straightforward algorithm. The following script achieves this:
<?php // Extract the first two characters from the HTTP_ACCEPT_LANGUAGE header as the browser language. $lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2); // Define a list of supported languages. $acceptLang = ['fr', 'it', 'en']; // Check if the browser language is in the supported list. $lang = in_array($lang, $acceptLang) ? $lang : 'en'; // Include the appropriate language-specific page. require_once "index_{$lang}.php"; ?>
This script operates as follows:
The above is the detailed content of How Can I Reliably Detect Browser Language in PHP?. For more information, please follow other related articles on the PHP Chinese website!