Sessions and Cookies are two related technologies that are used to store and access data when users interact with a website. The concept of sessions and cookies was first introduced by Netscape in 1995. They were originally used as a means of tracking user information to personalize the user’s experience on a website.
What is a cookie and how to create and use one?
A cookie is a small text file that a website stores on a user’s computer or mobile device when they visit the site. Cookies are used to remember users’ preferences, login information, and browsing history, among other things. They are also used to track users as they navigate different pages on a website and to collect information about their browsing habits.
When a user visits a website, the website sends a cookie to the user’s computer or mobile device. The user’s browser stores the cookie and sends it back to the website with every subsequent request. This allows the website to recognize the user and provide a personalized experience, such as by remembering their login information or preferences.
Cookies are typically stored in the user’s browser’s “cookies” or “local storage” folder. The information stored in a cookie is specific to the website that created it and can only be accessed by that website.
Cookies can have different properties, such as:
name
: the name of the cookievalue
: the value of the cookieexpiry date
: the date when the cookie will expirepath
: the path for which the cookie is validdomain
: the domain for which the cookie is validsecure
: whether the cookie should only be sent over a secure connectionHttpOnly
: whether the cookie should only be accessible through the HTTP protocol
Cookies can be used for both good and bad purposes. Some websites use cookies to personalize the user’s experience and provide more relevant content, while others use them to track users’ browsing habits for targeted advertising. Some websites also use cookies to store login information, so users don’t have to enter their login credentials every time they visit the site.
However, cookies can also be used to track users without their knowledge or consent, which can be a violation of privacy. Additionally, cookies can be stolen or tampered with, which can lead to security vulnerabilities. Therefore, it is important for users to be aware of the use of cookies on websites they visit and to take steps to protect their privacy, such as clearing cookies regularly or disabling cookies in their browser.
# How to create a cookie in flask.
from flask import Flask, make_response
app = Flask(__name__)
@app.route('/')
def index():
# Create a cookie with a key of 'my_cookie' and a value of 'my_value'
resp = make_response("Setting a cookie")
resp.set_cookie('my_cookie', 'my_value')
return resp
if __name__ == '__main__':
app.run(debug=True)
In this example, when a user visits the index page, the server will create a cookie named “my_cookie” with the value “my_value” and add it to the response. This cookie will be stored on the client’s browser and sent with every subsequent request to the server.
You can also set other attributes to the cookie such as the max age, expires, and the secure flag.
resp.set_cookie('my_cookie', 'my_value', max_age=60*60*24*365, expires=datetime.datetime.now()+datetime.timedelta(days=365), secure=True)
This will set the cookie to last for 1 year (60 seconds * 60 minutes * 24 hours * 365 days) and set the expires attribute to the current time plus 1 year and also set the secure flag to True.
Please note that the example is for demonstration purpose only, you should not store sensitive data in cookies.
What is a session and how to create and use one?
A session is a way for a website to remember a user’s state and preferences across multiple requests. It allows a website to maintain a consistent state for a user as they navigate different pages on the site.
When a user visits a website, the website creates a new session for the user. A session is typically represented by a unique session ID, which is a long, randomly generated string. The session ID is stored on the server and is also sent to the user’s browser in the form of a cookie.
The user’s browser stores the session ID in a cookie and sends it back to the server with every subsequent request. The server uses the session ID to look up the user’s session and retrieve the information stored in it.
The information stored in a session can include things like the user’s login information, preferences, and shopping cart contents. The server can use this information to personalize the user’s experience and provide more relevant content.
Sessions are stored on the server, and they are typically stored in memory, but they can also be stored in a database. Unlike cookies, which are stored on the user’s browser, sessions are stored on the server and are not accessible to the user.
Sessions have a expiration time, after which they will be deleted, this can be done by setting the session.permanent = True
and then setting the app.permanent_session_lifetime = timedelta(minutes=20)
, this will set the session to expire after 20 minutes of inactivity.
Sessions are useful for maintaining state across multiple requests, but they also introduce some security risks. For example, if an attacker is able to steal a user’s session ID, they can use it to impersonate the user and gain unauthorized access to the site. To mitigate these risks, it is important to use secure session ID generation, storage, and management.
Here is some example code for using sessions and cookies in a Python web application using the Flask framework:
from flask import Flask, session, redirect, url_for, escape, request
app = Flask(__name__)
# Set a secret key for the session
app.secret_key = 'your_secret_key'
@app.route('/')
def index():
if 'username' in session:
username = session['username']
return 'Logged in as ' + username + '<br>' + \
"<b><a href = '/logout'>click here to log out</a></b>"
return "You are not logged in <br><a href = '/login'></b>" + \
"click here to log in</b></a>"
@app.route('/login', methods = ['GET', 'POST'])
def login():
if request.method == 'POST':
session['username'] = request.form['username']
return redirect(url_for('index'))
return '''
<form method="post">
<p><input type=text name=username>
<p><input type=submit value=Login>
</form>
'''
@app.route('/logout')
def logout():
# remove the username from the session if it is there
session.pop('username', None)
return redirect(url_for('index'))
if __name__ == '__main__':
app.run(debug = True)
But they sound similar! What is the difference?
While cookies and sessions are both used to maintain state across multiple requests, they work in different ways and have some key differences:
- Storage location: Cookies are stored on the user’s browser, while sessions are stored on the server. This means that cookies are accessible to both the website and the user, while sessions are only accessible to the website.
- Accessibility: Cookies are sent with every request to the server and are accessible to both the website and the user. On the other hand, session data is only stored on the server and is not accessible to the user.
- Expiration: Cookies have an expiration date and will be deleted by the browser after that date, while sessions typically have a set expiration time after which they will be deleted by the server.
- Security: Because cookies are stored on the user’s browser, they are more vulnerable to being stolen or tampered with. Sessions are stored on the server and are more secure. However, if an attacker is able to steal a user’s session ID, they can use it to impersonate the user and gain unauthorized access to the site.
- Uses: Cookies are used to remember a user’s preferences and login information, while sessions are used to maintain state across multiple requests. Cookies can also be used to track users as they navigate different pages on a website and to collect information about their browsing habits.
Ok, so when to use what?
Cookies are best used for storing small amounts of data that do not contain sensitive information and will be needed on future requests, such as the user’s preferences or the contents of a shopping cart. Cookies are also useful for tracking users as they navigate different pages on a website and for collecting information about their browsing habits.
Sessions, on the other hand, are best used for storing more sensitive information, such as a user’s login information. Since session data is stored on the server, it is more secure than cookies, which are stored on the user’s browser and can be more easily stolen or tampered with. Sessions are also useful for maintaining state across multiple requests, such as when a user is filling out a form that spans multiple pages.
Additionally, you can use both cookies and sessions together, where session ID is stored in a cookie, and the actual session data is stored on the server. This way you can take advantage of the best of both worlds.