CodeBlanks Logo Icon CodeBlanks

Session vs cookie

PHP course · Intermediate · Lesson 92/115

Learn the difference between session and cookie and when to use each.

Session or cookie?

Session data is stored on the server; you write into $_SESSION. The user only carries an id cookie; the real data stays on the server.

A cookie is stored in the browser. The browser sends it back on every request; the server reads it.

Sessions are safer (the user does not see the data) and suit larger data. Cookies are for small, non-sensitive data like preferences (theme, language).

When to use which?

Session: for sensitive or larger data like the logged-in user id, cart total, role level. Stored on the server; the user cannot change it.

Cookie: for non-sensitive small data like theme (dark/light), language preference, a 'remember me' flag. Lives in the browser; can have an expiration.

Both can be used together: the session id is carried in a cookie. Never store sensitive data in a cookie.

Exercise Use session and cookie together

Call session_start(). Set $_SESSION['user_id'] = 42. Also set a one-day cookie with setcookie('last_visit', 'today', time() + 86400). Then echo stored.

Show example solution
Call session_start, set $_SESSION['user_id']=42, set the cookie with setcookie('last_visit', 'today', time() + 86400), then echo "stored".
Example solution:
<?php
// Start a session, set a cookie and print 'stored'
session_start();
$_SESSION['user_id'] = 42;
setcookie('last_visit', 'today', time() + 86400);
echo "stored\n";

Test yourself

  1. Which is stored on the server side?

    • $_COOKIE
    • Set-Cookie header
    • Browser memory
    • $_SESSION
    Show answer

    $_SESSION — Correct. $_SESSION data is kept on the server; the browser only carries an id cookie.

  2. Pick the right storage for a sensitive id

    <?php
    // Pick the right storage for sensitive data
    $choice = ['sensitive' => '____'];
    echo $choice['sensitive'];
    
    Show answer
    <?php
    // Pick the right storage for sensitive data
    $choice = ['sensitive' => 'session'];
    echo $choice['sensitive'];
    
  3. Match the session vs cookie differences

    $_SESSION
    Server side
    $_COOKIE
    In the browser
    ~4 KB limit
    For cookies
    Ends on browser close
    For sessions

All lessons in Intermediate