What are the best practices for handling language parameters in PHP URLs?

When handling language parameters in PHP URLs, it is important to properly sanitize and validate the input to prevent any security vulnerabilities. One approach is to use a whitelist of allowed languages and check if the language parameter matches one of the allowed values. Additionally, it is recommended to use a default language in case the parameter is not provided or is invalid.

// Define a whitelist of allowed languages
$allowedLanguages = ['en', 'es', 'fr'];

// Get the language parameter from the URL
$language = isset($_GET['lang']) ? $_GET['lang'] : 'en';

// Validate if the language is in the whitelist
if (!in_array($language, $allowedLanguages)) {
    $language = 'en'; // Set default language if invalid
}

// Use the $language variable in your code
echo "Selected language: " . $language;