What are best practices for setting and reading cookies in PHP to ensure proper functionality?

When setting and reading cookies in PHP, it is important to ensure proper functionality by setting the cookie before any output is sent to the browser and using secure and HttpOnly flags for sensitive cookies. Additionally, always sanitize and validate cookie data to prevent security vulnerabilities.

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

// Read the cookie
if(isset($_COOKIE['user'])){
    $user = $_COOKIE['user'];
    echo "Welcome back, $user!";
} else {
    echo "Cookie not set.";
}