What are the best practices for handling cookies in PHP to ensure data security and integrity?

When handling cookies in PHP, it is essential to ensure data security and integrity by properly sanitizing and validating the cookie data. This includes encrypting sensitive information before storing it in a cookie, setting secure flags to prevent cookie hijacking, and validating the cookie data before using it to prevent injection attacks.

// Set a secure cookie with encrypted data
$cookieData = encryptData($userData);
setcookie('secure_cookie', $cookieData, time() + 3600, '/', 'example.com', true, true);

// Retrieve and decrypt the cookie data
if(isset($_COOKIE['secure_cookie'])) {
    $userData = decryptData($_COOKIE['secure_cookie']);
    // Use the decrypted data safely
}