0
0
PHPprogramming~20 mins

Session variables in PHP - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Session Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this PHP session code?

Consider the following PHP code that uses session variables. What will be printed?

PHP
<?php
session_start();
$_SESSION['count'] = 1;
$_SESSION['count'] += 1;
echo $_SESSION['count'];
?>
A2
B1
C3
DUndefined index error
Attempts:
2 left
💡 Hint

Remember that session variables keep their values during the session and you can update them like normal variables.

Predict Output
intermediate
2:00remaining
What error does this PHP session code produce?

What error will this PHP code produce when run?

PHP
<?php
$_SESSION['user'] = 'Alice';
echo $_SESSION['user'];
?>
AWarning: session_start() not called
BNo error, outputs 'Alice'
CFatal error: Undefined variable 'SESSION'
DParse error: syntax error
Attempts:
2 left
💡 Hint

Session variables require a special function to be called before using them.

🔧 Debug
advanced
3:00remaining
Why does this PHP session code not keep the value?

This PHP code tries to count page visits using a session variable but always prints 1. Why?

PHP
<?php
session_start();
if (!isset($_SESSION['visits'])) {
    $_SESSION['visits'] = 1;
} else {
    $_SESSION['visits'] = 1;
}
echo $_SESSION['visits'];
?>
AThe variable 'visits' is not initialized before use
BThe else block resets 'visits' to 1 every time, so it never increments
CPHP sessions are disabled on the server
Dsession_start() is missing, so session variables don't work
Attempts:
2 left
💡 Hint

Look carefully at what happens inside the else block.

Predict Output
advanced
2:00remaining
What is the output of this PHP session code with unset?

What will this PHP code output?

PHP
<?php
session_start();
$_SESSION['name'] = 'Bob';
unset($_SESSION['name']);
echo isset($_SESSION['name']) ? $_SESSION['name'] : 'No name';
?>
AEmpty string
BBob
CUndefined index error
DNo name
Attempts:
2 left
💡 Hint

What does unset() do to a session variable?

Predict Output
expert
3:00remaining
What is the output of this PHP session code with session_destroy?

What will this PHP code output?

PHP
<?php
session_start();
$_SESSION['color'] = 'red';
session_destroy();
echo isset($_SESSION['color']) ? $_SESSION['color'] : 'No color';
?>
AWarning: session has been destroyed
BNo color
Cred
DEmpty string
Attempts:
2 left
💡 Hint

Does session_destroy() immediately clear the $_SESSION array in the current script?