Consider this PHP code snippet that uses sessions to store a user's name. What will be printed?
<?php session_start(); $_SESSION['user'] = 'Alice'; echo $_SESSION['user']; ?>
Sessions store data on the server and can be accessed after starting the session.
The code starts a session and sets the 'user' key in the session array to 'Alice'. Then it prints that value, so the output is 'Alice'.
Which situation is best suited for using cookies rather than sessions?
Think about where cookies and sessions store data and their lifetime.
Cookies are stored on the user's browser and can persist after closing it, making them good for preferences. Sessions store data on the server and usually expire when the browser closes.
What error will this PHP code produce when trying to access a cookie that is not set?
<?php echo $_COOKIE['theme']; ?>
Accessing an unset array key in PHP triggers a notice.
Trying to access a cookie key that does not exist causes a PHP notice about an undefined index.
Choose the best reason why sessions are considered more secure than cookies for storing sensitive information.
Think about where the data is stored and who can access it.
Sessions keep data on the server, so it is not exposed to the user's browser or potential attackers, unlike cookies which are stored on the client side.
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']; unset($_SESSION['user']); $_SESSION['logged_in'] = true; ?>
Remember that unset removes a key from the session array.
The code sets 'user' and 'cart', then removes 'user', and adds 'logged_in'. So only 'cart' and 'logged_in' remain, totaling 2 items.