This is the frequently asked interview question when you are applying for the role of a Web Developer. So today here we will be walking through the main difference between the Sessions and Cookies.
First of all, know that both the Sessions and Cookies are used to store information but sessions get stored on the client as well as a server while cookies are only stored on the client-side machine.
Session
A session creates a file in a temporary directory on the server where registered session variables and their values are stored. This data will be available to all pages on the site during that visit.
A session ends when the user closes the browser or after leaving the site, the server will terminate the session after a predetermined period of time. These session values are automatically deleted when the browser is closed so if you want to store the values permanently, then you should store them in the database.
Cookies
Cookies are text files stored on the client computer and they are kept of use for tracking purpose. The server script sends a set of cookies to the browser. For example name, age, or identification number etc. The browser stores this information on a local machine for future use and note that a cookie can only be read from the domain that it has been issued from.
When the browser sends any request to the web server then it sends those cookies information to the server and the server uses that information to identify the user.
When to use Sessions
To store important information such as the user id more securely on the server where malicious users cannot tamper with them. Sessions are used to pass values from one page to another.
When to use Cookies
HTTP is a stateless protocol; cookies allow us to track the state of the application using small files stored on the user’s computer. The path where the cookies are stored depends on the browser. Internet Explorer usually stores them in the Temporal Internet Files folder. Personalizing the user experience – this is achieved by allowing users to select their preferences. The page requested that follow are personalized based on the set preferences in the cookies. Tracking the pages visited by a user.
Summary and Key difference:-
- Cookies are client-side files that contain user information, whereas Sessions are server-side files that contain user information.
- A cookie is not dependent on the session, but Session is dependent on Cookie.
- A cookie expires depending on the lifetime you set for it, while a Session ends when a user closes his/her browser.
- The maximum cookie size is 4KB whereas, you can store as much data as you like in the session.
- The cookie does not have a function named unset cookie() while in Session you can use Session_destroy(); which is used to destroy all registered data or to unset some