What measures can be taken to ensure the security of a cookie-based login system in PHP?

To ensure the security of a cookie-based login system in PHP, it is important to use secure and HttpOnly flags for cookies, encrypt sensitive data stored in cookies, and implement measures to prevent common attacks like Cross-Site Scripting (XSS) and Cross-Site Request Forgery (CSRF).

// Set secure and HttpOnly flags for cookies
ini_set('session.cookie_secure', 1);
ini_set('session.cookie_httponly', 1);

// Encrypt sensitive data stored in cookies
$encrypted_data = openssl_encrypt($data, 'AES-256-CBC', $encryption_key, 0, $iv);
setcookie('encrypted_data', $encrypted_data, time() + 3600, '/', '', true, true);

// Implement measures to prevent XSS and CSRF attacks
// Use htmlspecialchars() when outputting user input
// Use CSRF tokens to validate form submissions