0
0
PHPprogramming~10 mins

Setting and reading cookies in PHP - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to set a cookie named "user" with value "Alice".

PHP
<?php
setcookie("user", [1]);
?>
Drag options to blanks, or click blank then click option'
A"Alice"
BAlice
C'user'
D"user"
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to put the cookie value in quotes.
Using the cookie name instead of the value.
2fill in blank
medium

Complete the code to read the cookie named "user" and store it in the variable $username.

PHP
<?php
$username = $_COOKIE[[1]];
?>
Drag options to blanks, or click blank then click option'
A'username'
Buser
C"user"
Dusername
Attempts:
3 left
💡 Hint
Common Mistakes
Using the cookie name without quotes.
Using the variable name instead of the cookie name.
3fill in blank
hard

Fix the error in the code to set a cookie that expires in 1 hour.

PHP
<?php
setcookie("session", "abc123", [1]);
?>
Drag options to blanks, or click blank then click option'
Atime() - 3600
B"3600"
C3600
Dtime() + 3600
Attempts:
3 left
💡 Hint
Common Mistakes
Using just 3600 instead of a timestamp.
Using a negative timestamp which deletes the cookie.
4fill in blank
hard

Fill both blanks to create a cookie named "theme" with value "dark" that expires in 7 days.

PHP
<?php
setcookie([1], [2], time() + 7 * 24 * 3600);
?>
Drag options to blanks, or click blank then click option'
A"theme"
B"dark"
C"user"
D"light"
Attempts:
3 left
💡 Hint
Common Mistakes
Swapping the name and value.
Forgetting quotes around strings.
5fill in blank
hard

Fill all three blanks to read the cookie "language" safely, providing a default value "en" if it does not exist.

PHP
<?php
$lang = isset($_COOKIE[[1]]) ? $_COOKIE[[2]] : [3];
?>
Drag options to blanks, or click blank then click option'
A"language"
C"en"
D"default"
Attempts:
3 left
💡 Hint
Common Mistakes
Using different strings for the cookie name in the two places.
Not providing a default value.