0
0
PHPprogramming~20 mins

Starting and using sessions 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 sessions. What will be printed when this script runs?

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

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

Predict Output
intermediate
2:00remaining
What will this PHP code output after two page loads?

This PHP script uses sessions to count visits. What will it output on the second page load?

PHP
<?php
session_start();
if (!isset($_SESSION['visits'])) {
    $_SESSION['visits'] = 0;
}
$_SESSION['visits'] += 1;
echo $_SESSION['visits'];
?>
A1
B0
CError: session not started
D2
Attempts:
2 left
💡 Hint

Remember the session variable keeps its value between page loads.

🔧 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
echo "Hello";
session_start();
$_SESSION['user'] = 'Alice';
?>
AThe session variable 'user' is not initialized
Bsession_start() is deprecated after echo
Csession_start() must be called before any output is sent
DYou cannot set session variables after echo
Attempts:
2 left
💡 Hint

Think about when PHP sends HTTP headers.

📝 Syntax
advanced
2:00remaining
Which option correctly starts a session and sets a variable?

Choose the correct PHP code that starts a session and sets the session variable 'role' to 'admin'.

A
&lt;?php
start_session();
$_SESSION['role'] = 'admin';
?&gt;
B
&lt;?php
session_start();
$_SESSION['role'] = 'admin';
?&gt;
C
&lt;?php
session_start;
$_SESSION['role'] = 'admin';
?&gt;
D
&lt;?php
session_start();
session['role'] = 'admin';
?&gt;
Attempts:
2 left
💡 Hint

Check the function name and syntax carefully.

🚀 Application
expert
3:00remaining
What is the value of $_SESSION['total'] after this code runs?

Given this PHP code, what will be the value of $_SESSION['total'] after execution?

PHP
<?php
session_start();
if (!isset($_SESSION['total'])) {
    $_SESSION['total'] = 5;
}
function addToTotal($value) {
    $_SESSION['total'] += $value;
}
addToTotal(10);
addToTotal(-3);
?>
A12
B15
C5
DError: Undefined index 'total'
Attempts:
2 left
💡 Hint

Calculate the additions step by step.