Consider the following PHP code that uses session variables. What will be printed?
<?php session_start(); $_SESSION['count'] = 1; $_SESSION['count'] += 1; echo $_SESSION['count']; ?>
Remember that session variables keep their values during the session and you can update them like normal variables.
The session variable 'count' is first set to 1, then incremented by 1, so the output is 2.
What error will this PHP code produce when run?
<?php $_SESSION['user'] = 'Alice'; echo $_SESSION['user']; ?>
Session variables require a special function to be called before using them.
Without session_start(), PHP produces a warning that the session has not been started. Accessing $_SESSION without starting the session is not recommended and may cause warnings or unexpected behavior.
This PHP code tries to count page visits using a session variable but always prints 1. Why?
<?php session_start(); if (!isset($_SESSION['visits'])) { $_SESSION['visits'] = 1; } else { $_SESSION['visits'] = 1; } echo $_SESSION['visits']; ?>
Look carefully at what happens inside the else block.
The else block sets 'visits' back to 1 every time, so the count never increases beyond 1.
What will this PHP code output?
<?php session_start(); $_SESSION['name'] = 'Bob'; unset($_SESSION['name']); echo isset($_SESSION['name']) ? $_SESSION['name'] : 'No name'; ?>
What does unset() do to a session variable?
unset() removes the session variable, so isset() returns false and 'No name' is printed.
What will this PHP code output?
<?php session_start(); $_SESSION['color'] = 'red'; session_destroy(); echo isset($_SESSION['color']) ? $_SESSION['color'] : 'No color'; ?>
Does session_destroy() immediately clear the $_SESSION array in the current script?
session_destroy() ends the session but does not clear the $_SESSION superglobal in the current script, so 'red' is printed.