Difference Between Cookies and Session

PHP sessions improve upon cookies because they allow web applications to store and retrieve more information than cookies. PHP sessions actually use cookies, but they add more functionality and security.

Sessions store data on the server, not on the browser like cookies

The main difference between a session and a cookie is that session data is stored on the server, whereas cookies store data in the visitor’s browser. Sessions use a session identifier to locate a particular user’s session data. This session identifier is normally stored in the user’s web browser in a cookie, but the sensitive data that needs to be more secure — like the user’s ID, name, etc. — will always stay on the server.

Sessions are more secure than cookies

So, why exactly should we use sessions when cookies work just fine? Well, as we already mentioned, sessions are more secure because the relevant information is stored on the server and not sent back and forth between the client and server. The second reason is that some users either turn off cookies or reject them.

Difference Between Cookies and Session

Sr. No.CookiesSession
1.Cookies are client-side files that can store some data on browsersSessions are server-side files that can store some data on servers.
2.We have to set cookie life (or expiration time) using PHP function setcookie()
setcookie("mobile", "123", time() + (86400 * 30), "/"); 
In this example, Cookie Name is “mobile”, Cookie Value is “123” and expiration time is: I hour after the current time (1 Hour = 86400 Seconds)
Mostly, Session Max lifetime is 1440 Seconds (24 Minutes) as defined in php.ini file. You can change it.
3.In PHP, $_COOKIE superglobal variable is used to get cookie data.In PHP, $_SESSION superglobal variable is used to set or delete the session data.
4.You don’t need any function to start Cookie as It is stored in your local machine.Before using $_SESSION, you have to call session_start();
This function will start the session and then, you can access $_SESSION data on that page.
5.Most browser’s maximum Cookie size is 4KB (4096 Bytes)You can store as much data as you like within in sessions.The only limits you can reach is the maximum memory a script can consume at one time, which by default is 128MB.
6.You can delete a cookie by providing any past date in expiration time parameter, It will automatically delete the cookie. There is no separate function to unset cookie.PHP functionsession_destroy() is used to destroy all data stored to a session, and if you want to unset a particular session variable then you can use PHP unset() function. Example: unset($_SESSION["name"])
7.Cookie ends depends on the lifetime you set for it.Session ends when user close his browser.

Learn more about the similar topics:
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
Difference Between Cookies and Session