CodeBlanks Logo Icon CodeBlanks

Login/logout logic

PHP course · Intermediate · Lesson 86/115

Learn to build a simple login and logout flow with sessions.

The login flow with sessions

A simple login flow works like this: the username and password are verified. If correct, a $_SESSION['user_id'] or $_SESSION['user'] identifier is written to the session.

On later pages, this identifier is checked with isset($_SESSION['user_id']). If defined, the user is logged in; protected pages are shown.

Never store the password in the session; keep only the user id or role. Password verification happens against the database.

Building the logout flow

Logout is the reverse of login. First remove the user variable with unset($_SESSION['user']). On later pages isset() then returns false.

Then close the whole session with session_destroy(). The session file is deleted; the user is fully logged out.

Tip: a logout.php page runs this code when the logout link is clicked. After logout, redirect to the login page.

Exercise Write a simple login check

Call session_start(). Set $username to 'admin' and $password to 'secret'. With an if, check both: if correct, set $_SESSION['user_id'] = 1 and print ok; in else, print denied.

Show example solution
Call session_start, set $username and $password, check both with === in an if, on success $_SESSION['user_id']=1 and echo ok, else echo denied.
Example solution:
<?php
// Simple login: write user_id to session on correct credentials
session_start();
$username = 'admin';
$password = 'secret';
if ($username === 'admin' && $password === 'secret') {
    $_SESSION['user_id'] = 1;
    echo "ok\n";
} else {
    echo "denied\n";
}

Test yourself

  1. What happens on a successful login?

    • session_destroy() is called
    • A user identifier is written to $_SESSION
    • session_id() is reset
    • The cookie is deleted
    Show answer

    A user identifier is written to $_SESSION — Correct. On login, a user identifier is written to $_SESSION; later pages read it.

  2. Write to the session on a successful login

    <?php
    session_start();
    if ($username === 'admin' && $password === 'secret') {
        ____
        echo 'login ok';
    } else {
        echo 'denied';
    }
    
    Show answer
    <?php
    session_start();
    if ($username === 'admin' && $password === 'secret') {
        $_SESSION['user'] = ['id' => 1];
        echo 'login ok';
    } else {
        echo 'denied';
    }
    
  3. Match the login and logout steps

    Login succeeds
    Write $_SESSION['user_id']
    Logout request
    unset + session_destroy
    $_SESSION['user_id']
    Check if logged in
    session_destroy()
    Closes the session fully

All lessons in Intermediate