0
0
PHPprogramming~20 mins

Setting and reading cookies in PHP - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Cookie 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 code that sets and reads a cookie?
Consider the following PHP code snippet that sets a cookie and then tries to read it immediately. What will be the output?
PHP
<?php
setcookie('user', 'Alice', time() + 3600);
if (isset($_COOKIE['user'])) {
    echo $_COOKIE['user'];
} else {
    echo 'No cookie found';
}
?>
AAlice
BEmpty string
CUndefined index error
DNo cookie found
Attempts:
2 left
💡 Hint
Remember that cookies set by setcookie() are not available until the next page load.
🧠 Conceptual
intermediate
1:00remaining
Which PHP function is used to set a cookie?
In PHP, which function is used to send a cookie to the browser?
Acookie_set()
Bsendcookie()
Csetcookie()
Dcreatecookie()
Attempts:
2 left
💡 Hint
The function name starts with 'set'.
Predict Output
advanced
1:30remaining
What will be the output of this PHP code reading a cookie?
Given the following PHP code, what will be the output if the cookie 'session' is set to 'xyz123'?
PHP
<?php
if (!empty($_COOKIE['session'])) {
    echo 'Session ID: ' . $_COOKIE['session'];
} else {
    echo 'No session cookie';
}
?>
ASession ID: xyz123
BNo session cookie
CUndefined index: session
DSession ID:
Attempts:
2 left
💡 Hint
Check if the cookie exists and is not empty.
🔧 Debug
advanced
2:00remaining
Why does this PHP code fail to delete a cookie?
Examine the code below. It tries to delete a cookie named 'theme' but fails. What is the reason?
PHP
<?php
setcookie('theme', '', time() + 3600);
if (!isset($_COOKIE['theme'])) {
    echo 'Cookie deleted';
} else {
    echo 'Cookie still exists';
}
?>
Asetcookie() cannot delete cookies
BThe expiration time should be in the past to delete a cookie
CCookie name is incorrect
DCookie value cannot be empty
Attempts:
2 left
💡 Hint
To delete a cookie, you must expire it immediately.
🚀 Application
expert
2:30remaining
How many cookies will be sent to the browser after this PHP script runs?
Consider this PHP script that sets multiple cookies. How many cookies will the browser receive?
PHP
<?php
setcookie('a', '1', time() + 3600);
setcookie('b', '2', time() + 3600, '/path1');
setcookie('c', '3', time() + 3600, '/path2');
setcookie('a', '4', time() + 3600, '/path1');
?>
A4
B1
C2
D3
Attempts:
2 left
💡 Hint
Cookies with the same name but different paths are treated as separate cookies.