What are the best practices for handling cookies and sessions in PHP to maintain user authentication?

To maintain user authentication in PHP, it is essential to handle cookies and sessions securely. Best practices include setting secure and HttpOnly flags on cookies, using HTTPS for secure communication, validating session data, and regenerating session IDs to prevent session fixation attacks.

// Start a secure session
session_start();

// Set session cookie parameters
session_set_cookie_params([
    'lifetime' => 3600,
    'path' => '/',
    'domain' => 'example.com',
    'secure' => true,
    'httponly' => true
]);

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

// Validate session data
if(isset($_SESSION['user_id'])) {
    // User is authenticated
} else {
    // Redirect to login page
    header("Location: login.php");
    exit();
}