PHP Sessions
Sessions store user data across multiple pages. Perfect for login systems, shopping carts, and maintaining user state throughout their visit!
Output
Click Run to execute your code
Starting a Session
<?php
// Must be called before any output
session_start();
// Now you can use $_SESSION
$_SESSION['user_id'] = 123;
$_SESSION['username'] = "john_doe";
?>
Reading Session Data
<?php
session_start();
if (isset($_SESSION['username'])) {
echo "Welcome back, " . $_SESSION['username'];
} else {
echo "Please log in";
}
?>
Destroying a Session (Logout)
<?php
session_start();
// Remove all session variables
session_unset();
// Destroy the session
session_destroy();
?>
Summary
- session_start(): Required before using $_SESSION
- $_SESSION: Store user data
- session_destroy(): Logout/clear session
- Server-side: More secure than cookies
What's Next?
Next, learn about Cookies - storing data on the client side!
Enjoying these tutorials?