What are some common pitfalls to watch out for when using sessions in PHP?

One common pitfall when using sessions in PHP is not properly initializing the session before trying to access or set session variables. To avoid this issue, always start the session at the beginning of your script using session_start(). Additionally, make sure to check if the session is already started before calling session_start() to prevent any errors.

<?php
// Always start the session before accessing or setting session variables
session_start();

// Check if the session is already started before calling session_start()
if(session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Now you can access and set session variables safely
$_SESSION['username'] = 'example_user';
?>