What are best practices for setting and accessing cookies in PHP to ensure data persistence?

When setting and accessing cookies in PHP, it is important to properly sanitize and validate the data being stored to prevent security vulnerabilities. It is also recommended to set appropriate expiration times for the cookies to ensure data persistence and to use secure and HTTP-only flags for added security.

// Setting a cookie with sanitized data and an expiration time of 1 hour
setcookie("user_id", filter_var($user_id, FILTER_SANITIZE_NUMBER_INT), time() + 3600, '/', '', true, true);

// Accessing the cookie value
$user_id = filter_input(INPUT_COOKIE, 'user_id', FILTER_SANITIZE_NUMBER_INT);