What are common pitfalls when setting and retrieving cookies in PHP?

Common pitfalls when setting and retrieving cookies in PHP include not setting the cookie before any output is sent to the browser, not properly encoding the cookie values, and not specifying the correct path or domain for the cookie. To solve these issues, make sure to set the cookie before any output is sent, use functions like urlencode() and urldecode() to properly encode and decode cookie values, and specify the path and domain parameters when setting the cookie.

<?php
// Set cookie before any output
setcookie('user', 'john_doe', time() + 3600, '/');

// Properly encode and decode cookie values
$value = urlencode('john_doe');
$value = urldecode($value);

// Specify path and domain for the cookie
setcookie('user', 'john_doe', time() + 3600, '/', 'example.com');
?>