Web Development /PHP Programming / Lesson
Web Development

Sessions and Cookies

Learn how PHP sessions and cookies maintain information between requests, start and manage sessions, store and retrieve session data, create and remove cookies, understand expiration and security considerations, and build practical login and preference workflows.

🎯

Learning Objectives

["Explain why HTTP sessions are needed in web applications.","Understand the difference between sessions and cookies.","Start and manage PHP sessions correctly.","Store and retrieve values using the $_SESSION superglobal.","Update and remove session variables.","Destroy a PHP session safely when appropriate.","Understand how cookies store small pieces of information in the browser.","Create cookies using setcookie().","Read cookie values using the $_COOKIE superglobal.","Set cookie expiration times and understand cookie lifetime.","Delete cookies by expiring them appropriately.","Understand important cookie security attributes such as Secure, HttpOnly, and SameSite.","Use sessions for server-side state such as authentication and temporary application data.","Understand why sensitive information should not be stored directly in ordinary cookies.","Build a simple practical session and cookie workflow."]

📖

Lesson Content

Introduction to Sessions and Cookies

Web applications communicate using HTTP requests and responses.
HTTP is largely stateless, which means that one request does not
automatically remember information from an earlier request.

For example, when a student logs into an online learning platform,
the application needs a way to recognize that student during later
requests.

PHP provides two important mechanisms for maintaining information
between requests:

  • Sessions
  • Cookies

Although sessions and cookies are related, they work differently and
should be used for different purposes.

1. What Is a Session?

A PHP session allows an application to maintain information across
multiple requests for a user.

Session data is stored on the server while the browser normally
carries a session identifier that allows PHP to associate subsequent
requests with the correct session.

This makes sessions useful for information such as:

  • Login state
  • Temporary user information
  • Shopping cart data
  • Multi-step form progress
  • Temporary messages
  • Application preferences

2. Starting a PHP Session

Before using the $_SESSION superglobal, PHP normally needs
to start or resume a session.

<?php

session_start();

?>

The session should normally be started before the application sends
output to the browser.

3. Storing Session Data

Once a session has started, values can be stored in the
$_SESSION superglobal.

<?php

session_start();

$_SESSION['student_name'] = 'Daniel';

?>

The value can then be available during later requests associated with
the same session.

4. Reading Session Data

<?php

session_start();

$name = $_SESSION['student_name'] ?? '';

echo htmlspecialchars(
    $name,
    ENT_QUOTES,
    'UTF-8'
);

?>

The null coalescing operator provides a safe default when the session
value does not exist.

5. Updating Session Data

Session values can be changed just like ordinary array values.

<?php

session_start();

$_SESSION['student_name'] = 'Michael';

?>

The new value will replace the previous value associated with that
session key.

6. Removing a Session Variable

The unset() function can remove an individual session
variable.

<?php

session_start();

unset($_SESSION['student_name']);

?>

This removes the selected value while allowing the rest of the session
data to remain available.

7. Destroying a Session

An application may need to destroy a session completely, such as when
a user logs out.

<?php

session_start();

$_SESSION = [];

session_destroy();

?>

Applications should handle logout and session cleanup carefully,
especially when sessions are used for authentication.

8. Sessions and Authentication

Sessions are commonly used to remember that a user has successfully
authenticated.

<?php

session_start();

$_SESSION['user_id'] = 25;
$_SESSION['logged_in'] = true;

?>

Later requests can check the session state.

<?php

session_start();

if (!empty($_SESSION['logged_in'])) {
    echo 'User is logged in.';
}

?>

A real authentication system requires additional security controls
and should not rely on a single session variable without proper
authentication and authorization logic.

9. Session Regeneration

When a user successfully authenticates, applications should consider
regenerating the session identifier.

<?php

session_start();

session_regenerate_id(true);

$_SESSION['user_id'] = 25;

?>

Regenerating the session identifier can help reduce the risk associated
with session fixation attacks.

10. What Is a Cookie?

A cookie is a small piece of data that a website can ask the browser
to store.

The browser can send applicable cookies back to the server with later
requests.

Cookies are commonly used for:

  • User preferences
  • Remembering selected options
  • Session identifiers
  • Application settings
  • Analytics and other web functionality

11. Creating a Cookie

PHP provides the setcookie() function for sending a
cookie to the browser.

<?php

setcookie(
    'student_name',
    'Daniel',
    time() + 3600,
    '/'
);

?>

This example requests that the browser store a cookie named
student_name.

12. Cookie Expiration

The expiration time determines how long the browser should retain the
cookie.

<?php

setcookie(
    'theme',
    'dark',
    time() + (30 * 24 * 60 * 60),
    '/'
);

?>

The example requests a cookie that expires approximately 30 days from
the current time.

13. Reading Cookies

Cookies sent by the browser are available through the
$_COOKIE superglobal.

<?php

$theme = $_COOKIE['theme'] ?? 'light';

echo htmlspecialchars(
    $theme,
    ENT_QUOTES,
    'UTF-8'
);

?>

Like other request data, cookie values should be treated as
untrusted input.

14. Deleting a Cookie

A cookie can normally be removed by sending the same cookie name with
an expiration time in the past.

<?php

setcookie(
    'theme',
    '',
    time() - 3600,
    '/'
);

?>

The path and other relevant cookie attributes should match the cookie
that was originally created.

15. Session Versus Cookie

SessionCookie
Session data is primarily maintained on the server.Cookie data is stored by the browser.
Useful for server-side application state.Useful for small browser-stored values and preferences.
Commonly used for authentication state.Can contain a session identifier.
Usually associated with a session identifier.Sent with requests that match its cookie rules.
Can hold application data that should remain server-side.Should not be trusted as authoritative application state.

16. Cookies Are Controlled by the Client

A browser can modify, remove, block, or refuse cookies.

Therefore, an application should never assume that a cookie value is
trustworthy simply because the server originally created the cookie.

<?php

$role = $_COOKIE['role'] ?? '';

if ($role === 'admin') {
    // Do not rely on this alone for authorization.
}

?>

Authorization decisions should be based on trusted server-side
authentication and permission checks.

17. Cookie Security: Secure

The Secure attribute instructs the browser to send the
cookie over HTTPS connections.

<?php

setcookie(
    'session_preference',
    'active',
    time() + 3600,
    '/',
    '',
    true
);

?>

Applications handling sensitive information should use HTTPS and
appropriate cookie security attributes.

18. Cookie Security: HttpOnly

The HttpOnly attribute prevents normal JavaScript access
to the cookie through browser APIs such as document.cookie.

This can reduce exposure of cookies to certain client-side script
attacks.

Modern PHP versions allow cookie options to be supplied using an
associative array.

<?php

setcookie(
    'session_preference',
    'active',
    [
        'expires' => time() + 3600,
        'path' => '/',
        'secure' => true,
        'httponly' => true,
        'samesite' => 'Lax'
    ]
);

?>

19. Cookie Security: SameSite

The SameSite attribute controls how cookies are included
with cross-site requests.

Common values include:

  • Strict
  • Lax
  • None

Applications should choose an appropriate value based on their
authentication and cross-site requirements.

20. Setting a Secure Cookie With Modern PHP

<?php

setcookie(
    'student_preference',
    'dark',
    [
        'expires' => time() + (30 * 24 * 60 * 60),
        'path' => '/',
        'secure' => true,
        'httponly' => true,
        'samesite' => 'Lax'
    ]
);

?>

This configuration requests a cookie that is HTTPS-only, inaccessible
to ordinary JavaScript, and subject to the selected SameSite policy.

21. Session Data and Cookies Work Together

PHP sessions commonly rely on a cookie containing a session identifier.

The browser sends the identifier back to the server, allowing PHP to
locate the corresponding server-side session data.

Conceptually, the relationship can be represented as:

Browser
   |
   | Session Cookie
   v
PHP Server
   |
   | Session ID
   v
Server-side Session Data

22. Temporary Flash Messages With Sessions

Sessions can be used to store a temporary message that can be shown
after a redirect.

<?php

session_start();

$_SESSION['success_message'] =
    'Registration completed successfully.';

header('Location: success.php');
exit;

?>

The destination page can read and remove the message.

<?php

session_start();

$message = $_SESSION['success_message'] ?? '';

unset($_SESSION['success_message']);

if ($message !== '') {
    echo htmlspecialchars(
        $message,
        ENT_QUOTES,
        'UTF-8'
    );
}

?>

23. Session-Based Login Example

<?php

session_start();

$username = trim($_POST['username'] ?? '');
$password = $_POST['password'] ?? '';

if ($username !== '' && $password !== '') {

    // Authentication logic would run here.

    session_regenerate_id(true);

    $_SESSION['user_id'] = 25;
    $_SESSION['logged_in'] = true;

    header('Location: dashboard.php');
    exit;
}

?>

A production authentication system should use secure password
handling, proper authentication APIs, authorization checks, HTTPS,
CSRF protection where appropriate, and other security controls.

24. Checking Login State

<?php

session_start();

if (empty($_SESSION['logged_in'])) {
    header('Location: login.php');
    exit;
}

echo 'Welcome to the dashboard.';

?>

The actual authorization decision should be implemented using the
application’s trusted authentication and permission system.

25. Logging Out

A logout operation should invalidate the authenticated session.

<?php

session_start();

$_SESSION = [];

session_destroy();

header('Location: login.php');
exit;

?>

Production applications may also need to clear or invalidate relevant
authentication cookies and apply the session-management strategy used
by the application.

26. Session Data Should Be Kept Appropriate

Sessions are not a replacement for a database.

Session data should generally contain information needed temporarily
for the current user’s interaction with the application.

Large datasets and permanent records should normally be stored in an
appropriate database or other persistent storage system.

27. Cookies Should Be Small

Cookies are designed for small pieces of data and are sent with
applicable requests.

Storing unnecessary large amounts of information in cookies can
increase request overhead and create unnecessary security concerns.

28. Never Store Passwords in Cookies

Passwords and other highly sensitive authentication secrets should not
be stored directly in ordinary browser cookies.

Authentication systems should use established secure session and
credential-management mechanisms.

29. Session and Cookie Input Must Be Validated

Values read from $_COOKIE are controlled by the client and
should be validated before being used.

<?php

$language = $_COOKIE['language'] ?? '';

$allowedLanguages = [
    'en',
    'yo'
];

if (!in_array($language, $allowedLanguages, true)) {
    $language = 'en';
}

echo htmlspecialchars(
    $language,
    ENT_QUOTES,
    'UTF-8'
);

?>

30. Sessions and Cookies in WordPress

WordPress has its own authentication, cookie, nonce, and user-session
mechanisms.

When developing WordPress plugins and themes, developers should use
WordPress APIs and authentication facilities where appropriate rather
than creating a separate authentication system unnecessarily.

For example, WordPress provides functions such as
wp_set_auth_cookie(), wp_get_current_user(),
and nonce functions for different application requirements.

31. Common Session Mistakes

  • Using session variables without starting the session.
  • Starting a session after output has already been sent.
  • Trusting session-related identifiers without proper session management.
  • Failing to regenerate the session identifier after authentication.
  • Storing unnecessarily large amounts of data in sessions.
  • Using sessions as a replacement for permanent database storage.
  • Failing to invalidate authentication state during logout.

32. Common Cookie Mistakes

  • Storing passwords directly in cookies.
  • Trusting cookie values as authoritative security information.
  • Failing to use HTTPS for sensitive applications.
  • Ignoring Secure and HttpOnly attributes where appropriate.
  • Using inappropriate SameSite settings.
  • Storing unnecessary amounts of information in cookies.
  • Failing to validate cookie values.

33. Sessions and Cookies Security Checklist

  • Use HTTPS for authentication and sensitive data.
  • Regenerate session identifiers after authentication.
  • Use appropriate Secure cookie settings.
  • Use HttpOnly for cookies that do not need JavaScript access.
  • Choose an appropriate SameSite policy.
  • Never store plaintext passwords in cookies.
  • Treat cookie values as untrusted input.
  • Validate data before using it for important decisions.
  • Protect state-changing requests against CSRF where appropriate.
  • Use proper authentication and authorization controls.
  • Destroy or invalidate authentication state during logout.

34. Practical Session and Cookie Example

<?php

session_start();

if (!isset($_SESSION['visits'])) {
    $_SESSION['visits'] = 0;
}

$_SESSION['visits']++;

setcookie(
    'preferred_course',
    'web-development',
    [
        'expires' => time() + (30 * 24 * 60 * 60),
        'path' => '/',
        'secure' => true,
        'httponly' => true,
        'samesite' => 'Lax'
    ]
);

$preferredCourse =
    $_COOKIE['preferred_course'] ?? '';

echo '<p>Session visits: ';

echo (int) $_SESSION['visits'];

echo '</p>';

echo '<p>Preferred course: ';

echo htmlspecialchars(
    $preferredCourse,
    ENT_QUOTES,
    'UTF-8'
);

echo '</p>';

?>

35. Best Practices

  • Use sessions for appropriate server-side state.
  • Use cookies for small browser-side values and identifiers.
  • Never trust cookie values for authorization.
  • Do not store plaintext passwords in cookies.
  • Use HTTPS for sensitive applications.
  • Use Secure, HttpOnly, and SameSite attributes where appropriate.
  • Regenerate session identifiers after authentication.
  • Validate session and cookie data before using it.
  • Use proper logout and session invalidation.
  • Follow WordPress APIs when building WordPress applications.

Lesson Summary

Sessions and cookies allow web applications to maintain information
across multiple HTTP requests.

PHP sessions provide a convenient mechanism for storing application
state on the server. They are commonly used for authentication,
temporary data, shopping carts, and multi-step workflows.

Cookies are small pieces of information stored by the browser. They
can be useful for preferences and identifiers, but they are controlled
by the client and should never be treated as automatically trustworthy.

Secure applications should use HTTPS, validate input, regenerate
session identifiers after authentication, protect sensitive cookies
with appropriate attributes, and never store plaintext passwords in
cookies.

Understanding the relationship between sessions and cookies is an
essential part of building secure PHP applications and understanding
how modern web authentication systems maintain user state.

💻

Code Example

<?php

session_start();

$errors = [];

$name = trim($_POST['name'] ?? '');
$email = trim($_POST['email'] ?? '');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    if ($name === '') {
        $errors['name'] = 'Name is required.';
    }

    if (
        filter_var(
            $email,
            FILTER_VALIDATE_EMAIL
        ) === false
    ) {
        $errors['email'] = 'A valid email address is required.';
    }

    if (empty($errors)) {

        /*
         * In a real application, authenticate or
         * process the user here.
         */

        session_regenerate_id(true);

        $_SESSION['user_name'] = $name;
        $_SESSION['logged_in'] = true;

        setcookie(
            'preferred_course',
            'web-development',
            [
                'expires' => time() + (30 * 24 * 60 * 60),
                'path' => '/',
                'secure' => true,
                'httponly' => true,
                'samesite' => 'Lax'
            ]
        );

        header('Location: dashboard.php');
        exit;
    }
}

?>

<form method="post">

    <label for="name">
        Full Name
    </label>

    <input
        type="text"
        id="name"
        name="name"
        value="<?php echo htmlspecialchars(
            $name,
            ENT_QUOTES,
            'UTF-8'
        ); ?>"
    >

    <?php if (isset($errors['name'])) : ?>

        <p>
            <?php
            echo htmlspecialchars(
                $errors['name'],
                ENT_QUOTES,
                'UTF-8'
            );
            ?>
        </p>

    <?php endif; ?>

    <label for="email">
        Email
    </label>

    <input
        type="email"
        id="email"
        name="email"
        value="<?php echo htmlspecialchars(
            $email,
            ENT_QUOTES,
            'UTF-8'
        ); ?>"
    >

    <?php if (isset($errors['email'])) : ?>

        <p>
            <?php
            echo htmlspecialchars(
                $errors['email'],
                ENT_QUOTES,
                'UTF-8'
            );
            ?>
        </p>

    <?php endif; ?>

    <button type="submit">
        Continue
    </button>

</form>
⭐

Key Takeaways

["PHP sessions maintain server-side information across multiple requests.","The $_SESSION superglobal is used to store and retrieve session values.","session_start() normally needs to run before using session data.","Sessions are commonly used for authentication state, temporary data, and multi-step workflows.","session_regenerate_id() should be considered after successful authentication.","Cookies are small pieces of data stored by the browser.","PHP creates cookies using setcookie() and reads them through $_COOKIE.","Cookie values are controlled by the client and must be treated as untrusted input.","Sensitive passwords should never be stored directly in ordinary cookies.","Secure, HttpOnly, and SameSite are important cookie security attributes.","HTTPS is essential when applications handle authentication or sensitive information.","WordPress applications should use WordPress authentication, cookie, nonce, and user APIs where appropriate."]

Enjoying this lesson?

Sign in to your Dwallnet Academy student account to track your learning progress and mark lessons as complete.

Sign In to Track Progress