
Keep a preference separate from session state
A visitor preference can be remembered in a cookie, while a session associates server-side data with a request. Treat a preference arriving from a browser as input and check it against the options your program supports.
A visitor preference can be remembered in a cookie, while a session associates server-side data with a request. Treat a preference arriving from a browser as input and check it against the options your program supports.
Walkthrough
Here the same function handles a missing value, an allowed language and an unfamiliar value. On a web request you can pass the cookie value into this function and store the result in the session.
PHP example
<?php
function languageChoice($input): string {
return in_array($input, ['en','ja','de'], true) ? $input : 'en';
}
foreach ([null, 'ja', 'unknown'] as $choice) {
echo languageChoice($choice), PHP_EOL;
}Expected output
en
ja
enChange and check
Try an empty value and the string JA. Decide whether uppercase language codes should be normalized before matching.
Discussion
Sign in to participate.



