How can cookies be utilized in PHP for user authentication and data storage?

Cookies can be utilized in PHP for user authentication by storing a unique identifier in the cookie when a user logs in. This identifier can then be used to verify the user's identity on subsequent visits. Cookies can also be used for data storage by storing user preferences or session information.

// Set a cookie for user authentication
$unique_id = generate_unique_id(); // Function to generate a unique identifier
setcookie('user_id', $unique_id, time() + 3600, '/');

// Retrieve the user's unique identifier from the cookie
$user_id = $_COOKIE['user_id'];

// Set a cookie for data storage
$user_preferences = ['theme' => 'dark', 'language' => 'en'];
setcookie('user_preferences', json_encode($user_preferences), time() + 3600, '/');

// Retrieve user preferences from the cookie
$user_preferences = json_decode($_COOKIE['user_preferences'], true);