Francisco Almeida
Introduction to Cookies
handling cookies in the context of Drupal
Francisco Almeida
(Co Founder Pictonio + Drupal Developer)
https://pictonio.com (# IS HIRING #)
Enjoy the rest of the Event
Introduction to Cookies
Reference: https://httpwg.org/http-extensions/draft-ietf-httpbis-rfc6265bis.html
What are Cookies?
![]()
Purpose of Cookies
Main purposes
Lifecycle of Cookies:
// Function to get all cookies function listCookies() { const cookies = document.cookie.split("; "); if (cookies.length === 0) { console.log("No cookies found on this page."); return; } console.log("Cookies on this page:"); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].split("="); const name = decodeURIComponent(cookie[0]); const value = decodeURIComponent(cookie[1]); console.log(`${name}: ${value}`); } } // Call the function to list all cookies listCookies();
// Function to get all cookies function listCookies() { const cookies = document.cookie.split("; "); if (cookies.length === 0) { console.log("No cookies found on this page."); return; } console.log("Cookies on this page:"); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].split("="); const name = decodeURIComponent(cookie[0]); const value = decodeURIComponent(cookie[1]); console.log(`${name}: ${value}`); } } // Call the function to list all cookies listCookies();
// Function to delete a cookie function deleteCookie(name) { document.cookie = name + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"; console.log(`Deleted cookie: ${name}`); } // Function to delete all cookies function deleteAllCookies() { const cookies = document.cookie.split("; "); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].split("="); deleteCookie(cookie[0]); } console.log("All cookies deleted."); } // Call the function to delete all cookies deleteAllCookies();
In the context of Drupal, cookies play a crucial role in various aspects of website functionality. Here's a more detailed exploration of how cookies are used in Drupal:
Drupal uses cookies to manage user sessions. When a user logs in, a session cookie is often created. This cookie helps Drupal identify the user as they navigate the website, ensuring they remain logged in until they explicitly log out or the session expires.
Cookies are used to authenticate users. Drupal sets cookies to validate that a user has the necessary permissions to access certain parts of the site. If a user doesn't have the right permissions or is not authenticated, they may be redirected to a login page.
Cookies can store user preferences and settings. For example, a user might choose a specific language, theme, or content layout. Drupal can use cookies to remember these preferences and apply them whenever the user visits the site.
Cookies can be used for tracking user behavior. Drupal can integrate with analytics tools that use cookies to gather data about how users interact with the website. This information is valuable for improving the user experience and content delivery.
Drupal uses cookies as part of its security measures. Cross-Site Request Forgery (CSRF) protection relies on cookies to confirm that a form submission comes from an authenticated and authorized user.
Drupal can use cookies to control caching. For example, if a user is logged in, personalized content might not be cached to ensure that each user sees their unique content.
Reference: https://www.lakedrops.com/en/blog/control-drupals-page-cache-cookies
When integrating third-party services like social media plugins or advertising networks, Drupal might use cookies to facilitate these integrations.
These third-party cookies can raise privacy and compliance considerations.
In e-commerce sites built with Drupal, cookies are used to remember the contents of a user's shopping cart, even if they navigate away from the cart page.
Drupal provides tools for handling cookie consent in compliance with privacy regulations like GDPR. Websites can use Drupal modules to display cookie consent banners and allow users to manage their cookie preferences.
Problem: https://www.drupal.org/project/cookies/issues/3364470
Drupal allows developers to create and manage custom cookies for specific site requirements. These cookies can store data that enhances the user experience or supports specific site functionalities.
Customizing cookie handling in Drupal modules and themes allows you to tailor how cookies are created, manipulated, and used to meet specific requirements.
1. Creating a Custom Cookie in a Module: You can create a custom cookie in a Drupal module to store and retrieve specific data. Example:
/**
* Controller function to set a custom cookie.
*/
public function setCustomCookie()
{
// Define the cookie parameters.
$cookieName = 'custom_cookie';
$cookieValue = 'example_value';
$expiration = time() + 3600; // Cookie will expire in 1 hour (adjust as needed).
$path = '/';
$domain = ''; // Use your domain if needed, e.g., 'example.com'
$secure = TRUE; // Set to TRUE if the cookie should only be sent over HTTPS.
$httpOnly = TRUE; // Set to TRUE to make the cookie accessible only via HTTP, not JavaScript.
// Create a new Cookie instance.
$cookie = new Cookie(
$cookieName,
$cookieValue,
$expiration,
$path,
$domain,
$secure,
$httpOnly
);
// Create a response object and add the cookie to it.
$response = new Response();
$response->headers->setCookie($cookie);
// Return the response.
return $response;
}2. Reading a Custom Cookie: You can read the value of a custom cookie in your module or theme when needed. For example:
// Read the custom cookie.
$cookie_name = 'custom_cookie';
$cookie_value = \Drupal::request()->cookies->get($cookie_name);
// Use the cookie value.
if (!empty($cookie_value)) {
// Do something with $cookie_value.
}3. Modifying a Custom Cookie: You can modify the value or parameters of a custom cookie during a user's session:
use Symfony\Component\HttpFoundation\Cookie;
// Retrieve the existing cookie value.
$cookie_name = 'custom_cookie';
$cookie_value = \Drupal::request()->cookies->get($cookie_name);
// Modify the value.
$new_value = 'new_example_value';
// Update the existing cookie.
$cookie = new Cookie(
$cookie_name,
$new_value,
$expiration,
$path,
$domain,
$secure,
$http_only
);
// Add the updated cookie to the response.
\Drupal::response()->headers->setCookie($cookie);4. Deleting a Custom Cookie: You can delete a custom cookie by setting its expiration time to a past date. This effectively removes the cookie from the user's browser:
use Symfony\Component\HttpFoundation\Cookie;
// Expire the custom cookie to delete it.
$cookie_name = 'custom_cookie';
$expiration = time() - 3600; // Set expiration to the past.
// Create an expired cookie.
$cookie = new Cookie(
$cookie_name,
'',
$expiration,
$path,
$domain,
$secure,
$http_only
);
// Add the expired cookie to the response to delete it.
\Drupal::response()->headers->setCookie($cookie);Presenting practical examples or scenarios to apply the knowledge learned during the session.
Use case 1
Problems
Solution
Use case 2
Solution
The COOKiES reCAPTCHA module integrates the drupal/recaptcha module to the COOKiES user consent management. The recaptcha widget will not be loaded and no trackable data will be sent to Google while users have not given their confirmation.
TODO: to be tested
Questions?
Which security feature prevents JavaScript from accessing cookies?