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 (requiressecure: 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).
This work is under a Attribution-NonCommercial-NoDerivatives 4.0 International license.
Desafíos de programación atemporales y multiparadigmáticos
Te encuentras ante un librillo de actividades, divididas en 2 niveles de dificultad. Te enfrentarás a los casos más comunes que te puedes encontrar en pruebas técnicas o aprender conceptos elementales de programación.
Buy the bookWill you buy me a coffee?
This is how I keep writing without ads or paywalls.
Sure, it's on me!
Comments
There are no comments yet.