What are some best practices for structuring conditional redirects based on user language preferences in PHP?

When redirecting users based on their language preferences in PHP, it is important to first detect the user's preferred language using headers or session variables. Once the language is determined, you can then use conditional statements to redirect the user to the appropriate page based on their language choice.

// Get the user's preferred language from headers or session variable
$userLanguage = $_SESSION['language']; // Assuming language is stored in session variable

// Define the URLs for different language versions of the website
$englishUrl = "http://example.com/en";
$frenchUrl = "http://example.com/fr";

// Redirect the user to the appropriate language version based on their preference
if($userLanguage == 'en') {
    header("Location: $englishUrl");
    exit();
} elseif($userLanguage == 'fr') {
    header("Location: $frenchUrl");
    exit();
} else {
    // Default to English if language preference is not set or not supported
    header("Location: $englishUrl");
    exit();
}