What are the best practices for setting and accessing cookies securely in PHP?

When setting and accessing cookies securely in PHP, it is important to use the correct flags to prevent common security vulnerabilities such as XSS and CSRF attacks. Setting the "HttpOnly" flag ensures that cookies are not accessible via JavaScript, while the "Secure" flag restricts cookies to be sent only over HTTPS connections. Additionally, setting the "SameSite" flag to "Strict" or "Lax" can help prevent CSRF attacks by restricting when cookies are sent in cross-origin requests.

// Set a secure cookie with HttpOnly, Secure, and SameSite flags
setcookie('cookie_name', 'cookie_value', [
    'expires' => time() + 3600,
    'path' => '/',
    'domain' => 'example.com',
    'secure' => true,
    'httponly' => true,
    'samesite' => 'Strict'
]);

// Access the secure cookie
$cookieValue = $_COOKIE['cookie_name'];