Home >Backend Development >PHP Tutorial >PHP realizes automatic selection of language jump on the homepage_PHP tutorial
Many websites make some links on the homepage to allow users to choose the respective language pages they want to visit, allowing Chinese to choose "Chinese", Koreans to choose "Korean", and so on. So can you make a program to automatically help with selection?
The answer is yes, everyone is using Google. If you use the Chinese system to open the Google homepage, the Chinese homepage will naturally open, not other languages. Because Google will automatically determine what is the preferred language used by the user's system.
How can we do it like Google? It’s actually very simple,
The HTTP Headers Information sent by the browser to the web server contains such information Accept-Language
This information is the language under Tools->Internet Options->General in the browser. It is used to set the language preferences acceptable to the browser. It can be a priority sequence for multiple acceptable languages.
Take PHP as an example below,
The language information acceptable to the user is placed in $_SERVER['HTTP_ACCEPT_LANGUAGE'],
The variable information is similar to "zh-cn". If it is a multi-language column, it is similar to "zh-cn,en;q=0.8,ko;q=0.5,zh-tw;q=0.3"
The following problems can be easily solved.
error_reporting(E_ALL ^ E_NOTICE);
// Analyze the attributes of HTTP_ACCEPT_LANGUAGE
// Only the first language setting is taken here (other functions can be enhanced as needed, here is only a simple method demonstration)
preg_match('/^([a-z-]+)/i', $_SERVER['HTTP_ACCEPT_LANGUAGE'], $matches);
$lang = $matches[1];
switch ($lang) {
case 'zh-cn' :
header('Location: [url]http://cn.example.com/[/url]');
Break;
case 'zh-tw' :
header('Location: [url]http://tw.example.com/[/url]');
Break;
case 'ko' :
header('Location: [url]http://ko.example.com/[/url]');
Break;
default:
header('Location: [url]http://en.example.com/[/url]');
Break;
}
?>