What are the best practices for managing session IDs in PHP applications?

Session IDs in PHP applications should be managed securely to prevent session hijacking and other security vulnerabilities. It is important to use secure cookies, regenerate session IDs after successful login, and validate session IDs before using them. Additionally, session data should be properly sanitized and validated to prevent injection attacks.

// Start a secure session
session_start([
    'cookie_lifetime' => 86400, // 1 day
    'cookie_httponly' => true,
    'cookie_secure' => true,
    'use_strict_mode' => true
]);

// Regenerate session ID after successful login
if ($loggedIn) {
    session_regenerate_id(true);
}

// Validate session ID before using it
if (!isset($_SESSION['user_id'])) {
    // Redirect to login page or handle unauthorized access
}

// Sanitize and validate session data
$user_id = filter_var($_SESSION['user_id'], FILTER_VALIDATE_INT);