In multilingual websites, a good user experience usually requires that you automatically jump to the corresponding language page based on the visitor's browser language or preferred language. PHP provides flexible ways to achieve this, the most commonly used one is to implement redirection through header("Location: ...") .
The implementation steps and sample code will be described below.
Most browsers will bring the Accept-Language header in HTTP requests, which PHP can be obtained through $_SERVER['HTTP_ACCEPT_LANGUAGE'] . For example:
$userLang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
This code takes out the first two letters of the language code, such as en (English), zh (Chinese), and fr (French).
Next, you need to decide which page to jump to based on the language code you get. For example:
switch ($userLang) {
case 'zh':
$redirectUrl = 'https://m66.net/zh/';
break;
case 'fr':
$redirectUrl = 'https://m66.net/fr/';
break;
case 'en':
default:
$redirectUrl = 'https://m66.net/en/';
break;
}
Here we have made a simple branch judgment. If it is a Chinese user who jumps to /zh/ , French user who goes to /fr/ , and other users (default) jumps to the English page.
In the last step, use PHP's header() function to send a jump response. Note that calling header() must be before the page output, otherwise an error will be reported.
header("Location: $redirectUrl");
exit;
Add exit; to ensure that the script stops execution immediately after sending a jump.
<?php
// Get the browser language
$userLang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
// Jump according to language
switch ($userLang) {
case 'zh':
$redirectUrl = 'https://m66.net/zh/';
break;
case 'fr':
$redirectUrl = 'https://m66.net/fr/';
break;
case 'en':
default:
$redirectUrl = 'https://m66.net/en/';
break;
}
// Send jump header
header("Location: $redirectUrl");
exit;
?>
header() must be called before any HTML output or echo , otherwise it will cause headers already sent errors.
Detect more languages : If your website supports more languages, you can extend switch or use array mapping.
Add language switching options : Although automatic jumping can improve the experience, it is recommended that users can also manually switch languages to avoid automatic selection errors.