Working With Cookies in Popular Web Frameworks
Cookies are a primary mechanism for maintaining state and identifying users in web applications. Being able to set, unset and check for cookies is an essential skill for web developers. In this article we'll cover how to set and unset cookies using PHP, Node.js, Laravel, Express and Flask.
Set Cookie
In web frameworks and languages, there are functions or methods to set a cookie with an expiration time. This stores the cookie data in the user's browser.
<?php
setcookie(
"cookie_name",
"cookie_value",
time() + 86400 // expires in 1 day
);
?>
<?php
Cookie::queue(
'cookie_name',
'cookie_value',
$minutes
);
// OR
request()->cookie(
'cookie_name',
'cookie_value',
$minutes
);
?>
var express = require('express');
var cookieParser = require('cookie-parser');
app.use(cookieParser());
var app = express();
app.get('/', function(req, res){
res.cookie(
"cookie_name",
"cookie_value",
{ maxAge: 86400000 } // 1 day
).send('');
});
response.set_cookie(
"cookie_name",
"cookie_value",
max_age=86400 # 1 day
)
Get all cookies
<?php
print_r($_COOKIE);
?>
<?php
request()->cookie();
?>
console.log('Cookies: ', req.cookies);
request.cookies
Get specific Cookie
<?php
$_COOKIE['cookie_name'];
?>
<?php
request()->cookie('cookie_name');
?>
req.cookies['cookie_name'];
request.cookies.get('cookie_name')
Unset Cookie
To unset a cookie, we simply set it again but with an expiration time in the past. This instructs the browser to delete that cookie.
<?php
setcookie(
"cookie_name",
"",
time() - 3600 // expires 1 hour ago
);
// OR
setcookie('cookie_name');
// OR
unset($_COOKIE['cookie_name']);
?>
<?php
Cookie::queue(
'cookie_name',
'null',
$minutes
);
?>
res.clearCookie('cookie_name');
response.set_cookie(
"cookie_name",
"",
max_age=0
)