CodeBlanks Logo Icon CodeBlanks

Starting a session with session_start()

PHP course · Intermediate · Lesson 82/115

Learn to start a session with session_start() and the session cookie.

What does session_start() do?

HTTP is stateless: each request is independent of the previous one. PHP overcomes this with session_start().

When you call it, PHP sends a session cookie to the browser and opens a separate data area on the server for each user. This area lives in the $_SESSION superglobal.

The cookie carries a unique session id; PHP uses it to find the right data. Call it once at the top of the page, before any output.

The session id and cookie

Every session has a unique identifier: the session id. PHP reads or sets it with session_id(). On the first session_start() call, the id is generated automatically.

The browser stores this id in a cookie named PHPSESSID (default). On later requests the browser sends the cookie back; PHP reads the id and loads the matching $_SESSION data.

You can rename the cookie in php.ini with session.name. The session lives until the cookie expires.

Exercise Print the session status with session_start

Call session_start(). Then, with an if, print active when session_status() equals PHP_SESSION_ACTIVE.

Show example solution
Call session_start, compare session_status() === PHP_SESSION_ACTIVE in an if, and echo "active".
Example solution:
<?php
// Call session_start and print that the session is active
session_start();
if (session_status() === PHP_SESSION_ACTIVE) {
    echo "active\n";
}

Test yourself

  1. When should session_start() be called?

    • At the very end, after all output
    • Before any output, at the top of the page
    • Only after a database connection
    • On the same line as echo
    Show answer

    Before any output, at the top of the page — Correct. session_start() must be called before output, or you get 'headers already sent'.

  2. Start the session

    <?php
    ____
    $_SESSION = ['counter' => 1];
    echo $_SESSION['counter'];
    
    Show answer
    <?php
    session_start();
    $_SESSION = ['counter' => 1];
    echo $_SESSION['counter'];
    
  3. Match the session concepts

    session_start()
    Starts the session
    $_SESSION
    Holds session data
    session_id()
    Returns the session id
    session_destroy()
    Destroys the session

All lessons in Intermediate