Consider the following PHP code that uses sessions. What will be printed when this script runs?
<?php session_start(); if (!isset($_SESSION['count'])) { $_SESSION['count'] = 1; } else { $_SESSION['count']++; } echo $_SESSION['count']; ?>
Think about what happens the first time the session variable is set.
The session variable 'count' is not set initially, so it is set to 1 and then printed. The output is 1.
This PHP script uses sessions to count visits. What will it output on the second page load?
<?php session_start(); if (!isset($_SESSION['visits'])) { $_SESSION['visits'] = 0; } $_SESSION['visits'] += 1; echo $_SESSION['visits']; ?>
Remember the session variable keeps its value between page loads.
On the first load, visits is set to 0 then incremented to 1. On the second load, it increments from 1 to 2, so output is 2.
Look at this PHP code snippet. It causes a warning about headers already sent. Why?
<?php echo "Hello"; session_start(); $_SESSION['user'] = 'Alice'; ?>
Think about when PHP sends HTTP headers.
session_start() sends HTTP headers. Headers must be sent before any output like echo. Here echo sends output first, causing the warning.
Choose the correct PHP code that starts a session and sets the session variable 'role' to 'admin'.
Check the function name and syntax carefully.
Only option B correctly calls session_start() as a function and uses $_SESSION superglobal properly.
Given this PHP code, what will be the value of $_SESSION['total'] after execution?
<?php session_start(); if (!isset($_SESSION['total'])) { $_SESSION['total'] = 5; } function addToTotal($value) { $_SESSION['total'] += $value; } addToTotal(10); addToTotal(-3); ?>
Calculate the additions step by step.
Initially total is 5. Then addToTotal(10) makes it 15. Then addToTotal(-3) reduces it to 12.