What are the potential pitfalls or errors that can occur when working with cookies in PHP?
One potential pitfall when working with cookies in PHP is not properly sanitizing the data stored in the cookie, which can lead to security vulnerabilities such as cross-site scripting attacks. To mitigate this risk, always sanitize and validate any data being stored in cookies before setting them.
// Sanitize and validate data before setting cookie
$user_id = filter_var($_POST['user_id'], FILTER_SANITIZE_NUMBER_INT);
setcookie('user_id', $user_id, time() + 3600, '/');