What are common pitfalls when using cookies in PHP?

One common pitfall when using cookies in PHP is not properly sanitizing and validating the data stored in the cookie. This can lead to security vulnerabilities such as XSS attacks or data manipulation. To mitigate this risk, always sanitize and validate any data before storing it in a cookie.

// Sanitize and validate data before storing in a cookie
$user_id = $_POST['user_id'];
$user_id = filter_var($user_id, FILTER_SANITIZE_NUMBER_INT);

setcookie('user_id', $user_id, time() + 3600, '/');