What are the best practices for managing sessions in PHP?

When managing sessions in PHP, it is important to ensure that session data is secure and properly handled to prevent unauthorized access or tampering. Best practices include setting a strong session ID, regenerating the session ID regularly, using HTTPS to encrypt session data, and validating and sanitizing session input.

// Start a secure session
session_start();

// Set a strong session ID
session_regenerate_id(true);

// Use HTTPS to encrypt session data
if (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] !== 'on') {
    header('Location: https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
    exit();
}

// Validate and sanitize session input
$_SESSION['user_id'] = filter_var($_SESSION['user_id'], FILTER_SANITIZE_NUMBER_INT);