PHP › Sessions & Cookies

What is a cookie, and how does it differ from a session in terms of where the actual data is stored?

Beginner

Answer

A cookie is a small piece of data that the server asks the visitor's browser to store and send back with future requests to the same website, and unlike a session, where the actual data lives on the server and only a small identifier is stored in the browser, a cookie can hold the actual data itself directly within the browser, though cookies are more limited in size and should never be used to store sensitive information since they are fully visible and editable by the person using the browser.
setcookie('theme_preference', 'dark', time() + (86400 * 30), '/');

echo $_COOKIE['theme_preference'] ?? 'light';
Real-world example A website remembers a visitor's preferred light or dark theme setting by storing that choice directly in a cookie, so the same preference is automatically applied the next time that visitor returns, even without needing to log in.

Common follow-ups: How long can a cookie realistically persist on a user's device?;Why should sensitive data never be stored directly inside a cookie?