What are best practices for securely storing user data in cookies using PHP?

When storing user data in cookies using PHP, it is important to ensure that sensitive information is encrypted and securely stored to prevent unauthorized access. One best practice is to use PHP's built-in encryption functions to encrypt the data before storing it in the cookie. Additionally, setting the secure and HttpOnly flags on the cookie can help protect against certain types of attacks.

// Encrypt and store user data in a cookie
$userData = [
    'username' => 'john_doe',
    'email' => 'john_doe@example.com'
];

// Encrypt user data
$encryptedUserData = openssl_encrypt(json_encode($userData), 'AES-256-CBC', 'secret_key', 0, '16characteriv');

// Set secure and HttpOnly flags on the cookie
setcookie('user_data', $encryptedUserData, time() + 3600, '/', 'example.com', true, true);