Bird
0
0

You want to store a user's preferred language in a session and retrieve it on another page. Which code snippet correctly does this?

hard📝 Application Q8 of 15
PHP - Sessions and Cookies
You want to store a user's preferred language in a session and retrieve it on another page. Which code snippet correctly does this?
A<?php session_destroy(); $_SESSION['lang'] = 'English'; ?>
B<?php session_start(); $_SESSION['lang'] = 'English'; ?>
C<?php $_SESSION['lang'] = 'English'; session_start(); ?>
D<?php setcookie('lang', 'English'); ?>
Step-by-Step Solution
Solution:
  1. Step 1: Correct order to start session and assign variable

    Call session_start() first, then assign $_SESSION['lang'].
  2. Step 2: Check other options

    <?php $_SESSION['lang'] = 'English'; session_start(); ?> assigns before starting session (wrong order), <?php session_destroy(); $_SESSION['lang'] = 'English'; ?> destroys session before assignment, <?php setcookie('lang', 'English'); ?> uses cookie instead of session.
  3. Final Answer:

    Start session first, then assign $_SESSION variable -> Option B
  4. Quick Check:

    session_start() before $_SESSION assignment [OK]
Quick Trick: Always start session before setting session variables [OK]
Common Mistakes:
  • Assigning $_SESSION before session_start()
  • Destroying session before assignment
  • Confusing cookies with sessions

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes