0
0
PHPprogramming~30 mins

How cookies work in PHP - Try It Yourself

Choose your learning style9 modes available
How cookies work
📖 Scenario: You are building a simple website that remembers a visitor's name using cookies. When the visitor enters their name, the website saves it in a cookie so that next time they visit, the site greets them by name automatically.
🎯 Goal: Create a PHP script that sets a cookie with the visitor's name, reads the cookie on subsequent visits, and displays a greeting message using the stored name.
📋 What You'll Learn
Create a variable to hold the visitor's name
Set a cookie with the visitor's name that expires in 1 hour
Check if the cookie exists and read the visitor's name from it
Display a greeting message using the visitor's name from the cookie
💡 Why This Matters
🌍 Real World
Cookies are used by websites to remember users and their preferences, making visits more personal and convenient.
💼 Career
Understanding how cookies work is important for web developers to manage user sessions, preferences, and authentication.
Progress0 / 4 steps
1
Create a variable with the visitor's name
Create a variable called $visitorName and set it to the string 'Alice'.
PHP
Need a hint?

Use $visitorName = 'Alice'; to create the variable.

2
Set a cookie with the visitor's name
Use the setcookie function to set a cookie named 'user' with the value of $visitorName that expires in 3600 seconds (1 hour).
PHP
Need a hint?

Use setcookie('user', $visitorName, time() + 3600); to set the cookie.

3
Check if the cookie exists and read its value
Use an if statement to check if the cookie named 'user' exists in $_COOKIE. If it exists, create a variable called $nameFromCookie and set it to the cookie's value.
PHP
Need a hint?

Use if (isset($_COOKIE['user'])) { $nameFromCookie = $_COOKIE['user']; } to read the cookie.

4
Display a greeting message using the cookie value
Use echo to print the greeting message Hello, followed by the value of $nameFromCookie. If $nameFromCookie is not set, print Hello, guest instead.
PHP
Need a hint?

Use echo "Hello, $nameFromCookie"; if the cookie exists, otherwise echo "Hello, guest";.