0
0
PHPprogramming~15 mins

How sessions work in PHP - Try It Yourself

Choose your learning style9 modes available
How sessions work in PHP
📖 Scenario: You are building a simple website that remembers a visitor's name during their visit. This helps the site greet them personally on each page.
🎯 Goal: Create a PHP script that starts a session, saves a visitor's name in the session, and then retrieves and displays that name on the page.
📋 What You'll Learn
Start a PHP session using session_start()
Create a session variable called user_name and assign it the value 'Alice'
Retrieve the user_name from the session
Display a greeting message using the session value
💡 Why This Matters
🌍 Real World
Sessions help websites remember who you are as you move between pages, like keeping your shopping cart or login info.
💼 Career
Understanding sessions is key for web developers to manage user data securely and create personalized experiences.
Progress0 / 4 steps
1
Start a PHP session
Write session_start(); at the beginning of your PHP script to start a session.
PHP
Need a hint?

Use the session_start() function at the very top of your PHP file.

2
Save a name in the session
After starting the session, create a session variable called user_name and set it to 'Alice' using $_SESSION.
PHP
Need a hint?

Use $_SESSION['user_name'] = 'Alice'; to store the name.

3
Retrieve the name from the session
Create a variable called name and assign it the value stored in the session variable user_name.
PHP
Need a hint?

Use $name = $_SESSION['user_name']; to get the stored name.

4
Display a greeting using the session name
Write a echo statement to display: Hello, Alice! Welcome back. using the variable $name.
PHP
Need a hint?

Use echo "Hello, $name! Welcome back."; to show the greeting.