0
0
PHPprogramming~30 mins

Setting and reading cookies in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
Setting and Reading Cookies in PHP
📖 Scenario: You are building a simple website that remembers a visitor's favorite color using cookies. When the visitor selects a color, the website saves it in a cookie. When the visitor returns, the website reads the cookie and shows the favorite color.
🎯 Goal: Create a PHP script that sets a cookie named favorite_color with a specific value, then reads and displays the cookie value if it exists.
📋 What You'll Learn
Create a cookie named favorite_color with the value blue
Set the cookie to expire in 1 hour
Check if the cookie favorite_color exists
Display the message Your favorite color is: blue if the cookie exists
Display No favorite color set if the cookie does not exist
💡 Why This Matters
🌍 Real World
Cookies are used on websites to remember user preferences, login status, and other information to improve user experience.
💼 Career
Web developers often need to set and read cookies to manage sessions, personalize content, and track user behavior.
Progress0 / 4 steps
1
Create a cookie named favorite_color
Write a line of PHP code to set a cookie named favorite_color with the value blue that expires in 1 hour using the setcookie function.
PHP
Need a hint?

Use setcookie("favorite_color", "blue", time() + 3600); to set the cookie.

2
Check if the cookie favorite_color exists
Add an if statement to check if the cookie favorite_color exists in the $_COOKIE superglobal array.
PHP
Need a hint?

Use isset($_COOKIE["favorite_color"]) to check if the cookie is set.

3
Display the favorite color if the cookie exists
Inside the if block, write a print statement to display Your favorite color is: followed by the cookie value $_COOKIE["favorite_color"]. Add an else block that prints No favorite color set.
PHP
Need a hint?

Use print("Your favorite color is: " . $_COOKIE["favorite_color"]) inside the if and print("No favorite color set") inside the else.

4
Run the script and see the output
Run the complete PHP script and observe the output. It should print Your favorite color is: blue if the cookie is set, or No favorite color set if not.
PHP
Need a hint?

Run the script in a browser or PHP server to see the cookie message.