What are the potential pitfalls of using session variables for user authentication in PHP?

Potential pitfalls of using session variables for user authentication in PHP include session hijacking, session fixation, and insecure session handling. To mitigate these risks, it is recommended to regenerate the session ID after a successful login to prevent session fixation and to use HTTPS to encrypt the session data in transit.

// Regenerate session ID after successful login
session_regenerate_id();

// Set session data securely
$_SESSION['user_id'] = $user_id;
$_SESSION['username'] = $username;