What potential pitfalls should be considered when setting cookies in PHP?

One potential pitfall when setting cookies in PHP is not properly sanitizing the data being 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 user input before setting it as a cookie.

// Sanitize and validate user input before setting it as a cookie
$user_input = $_POST['user_input'];
$clean_user_input = filter_var($user_input, FILTER_SANITIZE_STRING);

setcookie('user_data', $clean_user_input, time() + 3600, '/');