0
0
PHPprogramming~20 mins

How sessions work in PHP - Practice Exercises

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
PHP 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 this PHP script that uses sessions. What will it output?

PHP
<?php
session_start();
if (!isset($_SESSION['count'])) {
    $_SESSION['count'] = 1;
} else {
    $_SESSION['count']++;
}
echo $_SESSION['count'];
?>
A1
B0
CAn error about undefined index
DA blank page
Attempts:
2 left
💡 Hint

Think about what happens the first time the session variable is set.

🧠 Conceptual
intermediate
1:30remaining
What does session_start() do in PHP?

Choose the correct explanation of what session_start() does in PHP.

AIt initializes a session or resumes the current one based on a session identifier passed via a cookie or URL.
BIt destroys all session data and ends the session immediately.
CIt creates a new session file on the server without checking for existing sessions.
DIt encrypts all session variables automatically.
Attempts:
2 left
💡 Hint

Think about how PHP knows which session belongs to which user.

🔧 Debug
advanced
2:00remaining
Why does this PHP session code cause a warning?

Look at this PHP code snippet. It causes a warning about headers already sent. Why?

PHP
<?php
session_start();
echo "Hello";
session_start();
?>
ABecause <code>echo</code> cannot be used with sessions.
BBecause <code>session_start()</code> is called twice, and output was sent before the second call.
CBecause sessions must be started after all output is sent.
DBecause <code>session_start()</code> requires a parameter.
Attempts:
2 left
💡 Hint

Headers must be sent before any output. What happens if you call session_start() after output?

📝 Syntax
advanced
1:30remaining
Which option correctly sets a session variable in PHP?

Choose the correct way to set a session variable named user with value admin.

Aset_session('user', 'admin');
Bsession['user'] = 'admin';
C$_SESSION['user'] = 'admin';
Dsession->user = 'admin';
Attempts:
2 left
💡 Hint

Remember the superglobal array used for sessions.

🚀 Application
expert
2:00remaining
How many items are stored in the session after this code runs?

Given this PHP code, how many session variables exist after execution?

PHP
<?php
session_start();
$_SESSION['a'] = 1;
$_SESSION['b'] = 2;
unset($_SESSION['a']);
$_SESSION['c'] = 3;
?>
A3
B0
C1
D2
Attempts:
2 left
💡 Hint

Think about what unset() does to session variables.