What are common reasons for cookies not retaining their values in PHP applications?

Common reasons for cookies not retaining their values in PHP applications include not setting the cookie before any output is sent to the browser, setting incorrect expiration times, or not properly retrieving the cookie value when needed. To solve this issue, make sure to set the cookie before any output, double-check the expiration time, and correctly retrieve the cookie value using $_COOKIE.

<?php
// Set cookie before any output
setcookie("username", "John Doe", time() + 3600, "/");

// Retrieve cookie value
if(isset($_COOKIE['username'])) {
    $username = $_COOKIE['username'];
    echo "Welcome back, $username!";
} else {
    echo "Cookie not set.";
}
?>