What are some best practices for handling session IDs and cookies in PHP applications?

When handling session IDs and cookies in PHP applications, it is important to ensure that session IDs are securely generated and stored, and that cookies are set with appropriate security settings to prevent unauthorized access. Best practices include using session_regenerate_id() to generate a new session ID on each request, setting the session cookie to be secure and HttpOnly, and validating session data to prevent session hijacking.

// Generate a new session ID on each request
session_regenerate_id();

// Set session cookie with secure and HttpOnly flags
session_set_cookie_params([
    'lifetime' => 0,
    'path' => '/',
    'domain' => 'example.com',
    'secure' => true,
    'httponly' => true
]);

// Validate session data to prevent session hijacking
if (!isset($_SESSION['user_agent']) || $_SESSION['user_agent'] !== $_SERVER['HTTP_USER_AGENT']) {
    session_destroy();
}