Tutorials Logic, IN +91 8092939553 info@tutorialslogic.com
FAQs Support
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Interview Questions Website Development
Compiler Tutorials

PHP Sessions

Sessions store user data on the server (unlike cookies which store on the client). A unique session ID is sent to the browser as a cookie. Call session_start() at the top of every page that uses sessions.

Starting and Using Sessions

Session Basics
<?php
session_start(); // must be first line (before any output)

// Set session variables
$_SESSION['user_id']  = 42;
$_SESSION['username'] = 'Alice';
$_SESSION['role']     = 'admin';

// Read session variables
echo "User: " . $_SESSION['username'];
echo "Role: " . $_SESSION['role'];

// Check if session variable exists
if (isset($_SESSION['user_id'])) {
    echo "Logged in as user #" . $_SESSION['user_id'];
}

// Get session ID
echo session_id();

// Regenerate session ID (security best practice after login)
session_regenerate_id(true);
?>

Destroying Sessions

To fully log out a user, unset all session variables, destroy the session, and optionally delete the session cookie.

Destroying a Session
<?php
session_start();

// Remove a single variable
unset($_SESSION['username']);

// Remove all session variables
session_unset();

// Delete the session cookie
if (ini_get("session.use_cookies")) {
    $params = session_get_cookie_params();
    setcookie(session_name(), '', time() - 42000,
        $params["path"], $params["domain"],
        $params["secure"], $params["httponly"]
    );
}

// Destroy the session on the server
session_destroy();

header("Location: login.php");
exit;
?>

Practical Login Example

Login with Sessions
<?php
session_start();

// Redirect if already logged in
if (isset($_SESSION['user_id'])) {
    header("Location: dashboard.php");
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';

    // In production: query DB and use password_verify()
    if ($username === 'admin' && $password === 'secret') {
        session_regenerate_id(true); // prevent session fixation
        $_SESSION['user_id']  = 1;
        $_SESSION['username'] = $username;
        $_SESSION['login_time'] = time();
        header("Location: dashboard.php");
        exit;
    } else {
        $error = "Invalid credentials.";
    }
}
?>
<!-- dashboard.php -->
<?php
session_start();

// Session timeout after 30 minutes
$timeout = 1800;
if (isset($_SESSION['login_time']) &&
    (time() - $_SESSION['login_time']) > $timeout) {
    session_destroy();
    header("Location: login.php?msg=timeout");
    exit;
}
$_SESSION['login_time'] = time(); // reset timer

echo "Welcome, " . htmlspecialchars($_SESSION['username'] ?? 'Guest');
?>

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.