What is the best practice for setting and checking cookies in PHP?

When setting and checking cookies in PHP, it is important to properly sanitize and validate user input to prevent security vulnerabilities such as cross-site scripting attacks. It is also recommended to set the cookie parameters securely, including setting the 'secure' flag for HTTPS connections and 'httponly' flag to prevent access via JavaScript.

// Set a cookie with secure and httponly flags
setcookie('user', 'John Doe', time() + 3600, '/', '', true, true);

// Check if the cookie is set
if(isset($_COOKIE['user'])) {
    echo 'Welcome back, ' . $_COOKIE['user'];
} else {
    echo 'Welcome, guest';
}