Sobes.tech
Junior

What are cookies?

sobes.tech AI

Answer from AI

Cookies (HTTP cookies) are small pieces of data sent by a server to a user's web browser. The browser stores this data and sends it back with each subsequent request to the same server.

Main purposes:

  • State preservation: Allow the server to "remember" previous user actions or information between requests, as HTTP is a stateless protocol.
  • Personalization: Remembering user preferences such as language or theme.
  • Tracking: Can be used to track user behavior on the site or across sites (third-party cookies).
  • Session management: Storing session identifiers for user authentication.

Cookie structure: Mainly consists of a "name-value" pair and attributes defining scope and expiration (e.g., domain, path, expires, HttpOnly, Secure).

Example of setting a cookie in PHP:

<?php
// Set a cookie named 'username' with value 'john_doe'
// Expiration time 1 hour (3600 seconds) from now
setcookie('username', 'john_doe', time() + 3600, '/'); 

// Set a cookie named 'last_visit' with the current date and time
// Without expiration time - this is a session cookie, deleted when the browser closes
setcookie('last_visit', date('Y-m-d H:i:s'), 0, '/');
?>

Example of retrieving a cookie in PHP:

<?php
// Check if the 'username' cookie is set
if (isset($_COOKIE['username'])) {
    // Output the cookie value
    echo "Hello, " . htmlspecialchars($_COOKIE['username']) . "!";
} else {
    echo "Cookie 'username' not found.";
}
?>

Important: Cookies can be disabled by the user in browser settings. There are also size and quantity limits for cookies per domain. Security considerations, such as protection against XSS and CSRF, require proper use of cookie attributes (HttpOnly, Secure, SameSite).

What are cookies? — PHP - sobes.tech