What is the purpose of using cookies in PHP and what are the potential pitfalls when setting them?

Cookies in PHP are used to store small pieces of data on the client-side, allowing websites to remember user preferences and track user activity. When setting cookies, it is important to be mindful of potential security risks such as cookie tampering and cross-site scripting attacks. To mitigate these risks, always sanitize and validate user input before setting cookies.

// Sanitize and validate user input before setting cookies
$user_id = filter_input(INPUT_POST, 'user_id', FILTER_SANITIZE_NUMBER_INT);

if ($user_id) {
    setcookie('user_id', $user_id, time() + 3600, '/', 'example.com', true, true);
}