What are some potential pitfalls when working with PHP sessions and how can they be avoided?

One potential pitfall when working with PHP sessions is not properly securing them, which can lead to security vulnerabilities such as session hijacking or session fixation attacks. To avoid this, it is important to use secure session handling techniques such as regenerating the session ID after a user logs in or out, setting the session cookie parameters to be secure and HTTP only, and storing sensitive session data in server-side storage rather than client-side storage.

// Start secure session
session_start();

// Regenerate session ID to prevent session fixation attacks
session_regenerate_id(true);

// Set session cookie parameters to be secure and HTTP only
session_set_cookie_params([
    'secure' => true,
    'httponly' => true
]);

// Store sensitive session data in server-side storage
$_SESSION['user_id'] = $user_id;