What are the common pitfalls when using PHP sessions and how can they be avoided?

Common pitfalls when using PHP sessions include not starting the session before using any session variables, not properly destroying the session when it's no longer needed, and not properly securing the session data from unauthorized access. To avoid these pitfalls, always start the session at the beginning of your script, destroy the session when it's no longer needed, and use session_regenerate_id() to prevent session fixation attacks.

// Start the session
session_start();

// Use session variables
$_SESSION['user_id'] = 123;

// Destroy the session when it's no longer needed
session_destroy();

// Secure the session data from unauthorized access
session_regenerate_id(true);