What best practices should be followed when handling session data in PHP, especially in relation to security and error handling?

When handling session data in PHP, it is important to ensure proper security measures are in place to prevent unauthorized access. This includes using HTTPS, regenerating session IDs, and validating user input. Additionally, error handling should be implemented to gracefully handle any issues that may arise during session management.

// Start a secure session
session_set_cookie_params([
    'lifetime' => 0,
    'path' => '/',
    'domain' => 'example.com',
    'secure' => true,
    'httponly' => true,
    'samesite' => 'Strict'
]);
session_start();

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

// Validate user input before storing in session
if(isset($_POST['username']) && !empty($_POST['username'])) {
    $_SESSION['username'] = $_POST['username'];
} else {
    // Handle error
    echo "Invalid username";
}