What are the best practices for handling cookies in PHP scripts to ensure they are set and stored correctly?

To handle cookies correctly in PHP scripts, it is important to set them before any output is sent to the browser. This can be done using the setcookie() function with appropriate parameters such as the cookie name, value, expiration time, path, and domain. It is also crucial to sanitize and validate any data stored in cookies to prevent security vulnerabilities.

<?php
// Set a cookie with a name, value, expiration time, path, and domain
setcookie("user_id", "12345", time() + 3600, "/", "example.com");

// Retrieve and sanitize the cookie value
$user_id = filter_input(INPUT_COOKIE, 'user_id', FILTER_SANITIZE_STRING);
?>