What is the purpose of setting a cookie in PHP and what are common use cases for it?

Setting a cookie in PHP allows you to store data on the user's browser for future use. This can be useful for remembering user preferences, tracking user activity, or implementing features like shopping carts. Common use cases for setting cookies include remembering login credentials, storing user preferences, and tracking user behavior for analytics.

// Set a cookie with a name, value, expiration time, and path
setcookie("user_id", "12345", time() + 3600, "/");

// Retrieve the value of the cookie
$user_id = $_COOKIE["user_id"];

// Output the value of the cookie
echo "User ID: " . $user_id;