What are potential pitfalls when using PHP to store and retrieve cookies based on user input?

One potential pitfall when using PHP to store and retrieve cookies based on user input is not properly sanitizing and validating the user input, which can lead to security vulnerabilities such as XSS attacks. To mitigate this risk, always sanitize and validate user input before using it to set or retrieve cookies.

// Sanitize and validate user input before setting a cookie
$user_input = filter_input(INPUT_POST, 'user_input', FILTER_SANITIZE_STRING);
if($user_input){
    setcookie('user_cookie', $user_input, time() + 3600, '/');
}

// Retrieve and sanitize cookie value before using it
$user_cookie = filter_input(INPUT_COOKIE, 'user_cookie', FILTER_SANITIZE_STRING);
if($user_cookie){
    // Use the sanitized cookie value
}