Consider a simple PHP web application where a user logs in and browses pages. Why is state management important in this context?
Think about what happens when you open a new page in a browser after logging in.
HTTP does not keep track of previous requests. State management is needed to remember user information like login status between page visits.
What will this PHP code output when run twice in a browser session?
<?php session_start(); if (!isset($_SESSION['count'])) { $_SESSION['count'] = 1; } else { $_SESSION['count']++; } echo "Count: " . $_SESSION['count']; ?>
Sessions store data between page loads.
The code initializes a session variable 'count' to 1 if not set, else increments it. So first run shows 1, second run shows 2.
Look at this PHP code snippet. Why does the session variable not persist?
<?php // Page 1 session_start(); $_SESSION['user'] = 'Alice'; ?> <?php // Page 2 // Missing session_start() echo $_SESSION['user']; ?>
Check if session_start() is called on every page using session data.
PHP requires session_start() on every page to access session variables. Without it, $_SESSION is empty.
Choose the correct PHP code snippet that starts a session and sets a session variable 'role' to 'admin'.
session_start() must be called before using $_SESSION.
Option A correctly calls session_start() as a function before setting $_SESSION variable. Others have syntax errors or wrong order.
Given the following PHP code, how many key-value pairs are stored in the session?
<?php session_start(); $_SESSION['user'] = 'Bob'; $_SESSION['cart'] = ['apple', 'banana']; $_SESSION['cart'][] = 'orange'; unset($_SESSION['user']); ?>
Check which session keys remain after unset.
'user' is removed by unset, 'cart' remains with 3 items but counts as one key in $_SESSION.