0
0
PhpHow-ToBeginner · 4 min read

How to Use Sessions for Authentication in PHP: Simple Guide

Use session_start() to begin a session, then store user login status in $_SESSION variables after verifying credentials. Check these session variables on protected pages to allow or deny access.
📐

Syntax

To use sessions for authentication in PHP, you start the session with session_start(). Then, you can set session variables like $_SESSION['user'] to store user information after login. On other pages, check these variables to confirm the user is logged in.

php
<?php
session_start(); // Start the session

// Set a session variable after login
$_SESSION['user'] = 'username';

// Check if user is logged in
if (isset($_SESSION['user'])) {
    echo 'User is logged in as ' . $_SESSION['user'];
} else {
    echo 'User is not logged in';
}
?>
Output
User is logged in as username
💻

Example

This example shows a simple login check using sessions. It starts a session, verifies a hardcoded username and password, sets a session variable on success, and protects a page by checking the session.

php
<?php
// login.php
session_start();

// Hardcoded credentials for demo
$correct_user = 'admin';
$correct_pass = '1234';

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

    if ($user === $correct_user && $pass === $correct_pass) {
        $_SESSION['user'] = $user; // Store user in session
        echo 'Login successful!';
    } else {
        echo 'Invalid username or password.';
    }
} else {
    // Show simple login form
    echo '<form method="POST">
            Username: <input name="username"><br>
            Password: <input type="password" name="password"><br>
            <button type="submit">Login</button>
          </form>';
}

// protected.php
session_start();
if (!isset($_SESSION['user'])) {
    echo 'Access denied. Please log in.';
    exit;
}
echo 'Welcome, ' . $_SESSION['user'] . '! You are authenticated.';
?>
Output
Login successful! Welcome, admin! You are authenticated.
⚠️

Common Pitfalls

  • Forgetting to call session_start() at the beginning of every script that uses sessions.
  • Not validating user input before setting session variables.
  • Not destroying sessions on logout, which can leave users logged in.
  • Storing sensitive data directly in sessions without encryption.
php
<?php
// Wrong: Missing session_start()
echo isset($_SESSION['user']) ? 'Logged in' : 'Not logged in';

// Right:
session_start();
echo isset($_SESSION['user']) ? 'Logged in' : 'Not logged in';

// Logout example:
session_start();
session_unset();
session_destroy();
echo 'Logged out successfully.';
?>
Output
Logged out successfully.
📊

Quick Reference

Remember these key session functions for authentication:

  • session_start(): Begin or resume a session.
  • $_SESSION: Superglobal array to store user data.
  • session_unset(): Remove all session variables.
  • session_destroy(): End the session completely.

Key Takeaways

Always call session_start() before using sessions.
Store user login status in $_SESSION after verifying credentials.
Check session variables on protected pages to control access.
Destroy sessions properly on logout to secure user data.
Validate and sanitize all user inputs before using them.