12. Cookies

A Cookie, or permanent Cookie, is a variable that is stored in the browser with a lifetime period. The tasty thing about this feature is that if the user leaves our site and comes back later, we can recover the information. Unless they have deleted the Cookies from our website.

Despite the bad reputation they have, they are useful and safe for programmers; another thing is that there are unscrupulous companies that want to take advantage of their virtues. They have many uses:

  • Save your configuration to improve the experience (autologin, changing the language you chose the first time, the last search you performed, avoiding showing notices you already accepted...).
  • Commercial uses (personalized suggestions depending on what you searched for last time, saving your shopping cart...).
  • Create statistics.

Create

Traditional syntax:

setcookie('nombre', 'valor', 'caducidad');
// Will expire in 60 seconds
$caducidad = time() + 60;
setcookie('idioma', 'es', $caducidad);

Modern syntax (PHP 7.3+):

Since PHP 7.3 we can use an array of options for a clearer and safer configuration:

setcookie('idioma', 'es', [
    'expires' => time() + 60,
    'path' => '/',
    'domain' => '',
    'secure' => true,      // Only over HTTPS
    'httponly' => true,    // Not accessible from JavaScript
    'samesite' => 'Strict' // Protection against CSRF
]);

Recommended security options:

  • secure: true: The cookie will only be sent over HTTPS connections. Essential for production.
  • httponly: true: Prevents JavaScript from accessing the cookie, protecting against XSS (Cross-Site Scripting) attacks.
  • samesite: Protects against CSRF (Cross-Site Request Forgery) attacks:
  • 'Strict': The cookie is only sent in same-site requests (maximum security).
  • 'Lax': Allows sending the cookie in normal navigation from other sites (balance between security and usability).
  • 'None': Allows sending the cookie in third-party requests (requires secure: true).

Get

echo $_COOKIE['idioma'];
// es

Update

setcookie('idioma', 'fr');
echo $_COOKIE['idioma'];
// fr

Delete

unset($_COOKIE['idioma']);

Another way to delete a Cookie is to expire it: setcookie('idioma', 'es', time() - 1).

Building SPAs with Django and HTML Over the Wire: Learn to build real-time single page applications with Python

Building SPAs with Django and HTML Over the Wire: Learn to build real-time single page applications with Python

The HTML over WebSockets approach simplifies single-page application (SPA) development and lets you bypass learning a JavaScript rendering framework such as React, Vue, or Angular, moving the logic to Python. This web application development book provides you with all the Django tools you need to simplify your developments with real-time results.

Buy the book

Help me keep writing

Every coffee gives me a push toward the next article.

Comments

There are no comments yet.