Ah, sessions in PHP! You might be thinking, "What is this sorcery?" Well, imagine walking into a coffee shop ☕, and the barista remembers your order. That’s exactly what PHP Sessions do! They remember who you are across multiple pages. Pretty cool, right?
But wait! What about Cookies? Are they the same thing? Nope! Cookies live in the browser, sessions live on the server. Let’s dive into the magic of sessions, complete with an awesome real-world example!
What are PHP Sessions?
A PHP session stores user-specific information on the server, unlike cookies, which store data in the browser. This means: More secure (No sneaky user tampering!) No data limits (Unlike cookies, which have size restrictions!), Perfect for login systems, carts, and user preferences!
How does it work? User visits your site → A session starts. Server stores data (e.g., user ID, cart items). User navigates → The session remembers them!
Starting a Session
Before using a session, you MUST start it. Here’s how:
session_start(); // Always at the top!
$_SESSION["username"] = "CaptainPHP";
echo "Hello, " . $_SESSION["username"] . "!";
Pro Tip: Call session_start()
at the VERY TOP of your PHP files before outputting anything!
Accessing Session Data
Let’s retrieve stored session data:
session_start();
echo "Welcome back, " . $_SESSION["username"] . "!";
Boom! The server remembers you!
Destroying a Session (Logging Out)
When users log out, we should destroy their session:
session_start();
session_unset(); // Clears session variables
session_destroy(); // Ends the session
echo "You have been logged out!";
Pro Tip: Always destroy sessions when they’re no longer needed to free up server space!
Real-World Example: Login System
Let’s build a simple login system using PHP sessions!
Login Page (login.php)
session_start();
if ($_POST['username'] == 'admin' && $_POST['password'] == '1234') {
$_SESSION['user'] = 'admin';
echo "Login successful! <a href='dashboard.php'>Go to Dashboard</a>";
} else {
echo "Invalid credentials!";
}
Dashboard (dashboard.php)
session_start();
if (!isset($_SESSION['user'])) {
die("Access denied! <a href='login.php'>Login here</a>");
}
echo "Welcome, " . $_SESSION['user'] . "! <a href='logout.php'>Logout</a>";
Logout Page (logout.php)
session_start();
session_destroy();
echo "Logged out! <a href='login.php'>Login again</a>";
Now you have a secure login system using PHP sessions!
PHP sessions are an awesome way to keep track of users securely. You’ve now learned how to: Start and use sessions, Store and retrieve session data, Destroy sessions for logout, Build a basic login system.
0 Comments