</>
Skip to content
PHP lessons (30/49)

PHP — Sessions

Starting a session

<?php
session_start();

// Set session variable
$_SESSION['username'] = 'Alice';
$_SESSION['logged_in'] = true;

// Access session variable
echo $_SESSION['username'];
?>

Session operations

<?php
session_start();

// Check if set
if (isset($_SESSION['username'])) {
    echo "Welcome, " . $_SESSION['username'];
}

// Destroy session
session_unset();
session_destroy();
?>

Session with database

<?php
session_start();

// Login
function login(string $username, string $password): bool {
    // Verify credentials
    $valid = verifyCredentials($username, $password);
    if ($valid) {
        $_SESSION['user_id'] = getUserId($username);
        $_SESSION['username'] = $username;
        return true;
    }
    return false;
}

// Check login
function isLoggedIn(): bool {
    return isset($_SESSION['user_id']);
}

// Logout
function logout(): void {
    session_unset();
    session_destroy();
}
?>

Session configuration

<?php
// Set session cookie parameters
session_set_cookie_params([
    'lifetime' => 3600,
    'path' => '/',
    'domain' => 'example.com',
    'secure' => true,
    'httponly' => true,
    'samesite' => 'Strict'
]);

session_start();
?>

Mini Practice

Write PHP code that:

  1. Starts a session and sets variables
  2. Checks if a session variable exists
  3. Destroys a session
  4. Configures session cookie parameters

Up Next

In the next lesson, you'll learn about Cookies — working with cookies.

Related Topics

Frequently Asked Questions about Sessions

What is Sessions in PHP?

Sessions is a fundamental concept in PHP. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Sessions?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Sessions.

Why is Sessions important in PHP?

Sessions is essential for PHP development. Understanding this concept will help you write better code and solve real-world problems more effectively.