What are some best practices for handling sessions in PHP to avoid security vulnerabilities?

To avoid security vulnerabilities when handling sessions in PHP, it is important to use secure session handling techniques such as setting session cookie parameters properly, regenerating session IDs, and validating session data to prevent session fixation attacks.

// Start a secure session
session_start([
    'cookie_lifetime' => 86400, // set cookie lifetime to 1 day
    'cookie_httponly' => true, // prevent client-side script access to the cookie
    'cookie_secure' => true, // only send cookie over HTTPS
]);

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

// Validate session data before using it
if(isset($_SESSION['user_id'])){
    // Proceed with using session data
} else {
    // Handle unauthorized access
}