Site icon RankWatch Blog

How Sessions Work on PHP?


How session works in PHP?
In the development-cycle of PHP, almost all the developers use sessions for storing information on the server side, and its quite satisfying when they read and write a value from PHPs, but what is the need of sessions?? How does it exactly work?? Let’s cover all points one by one…

What are PHP Sessions?
A PHP Session is a global variable which is used to store user data or any other useful data for a particular period across a web application.

Why do we need Sessions?
Basically, HTTP is a stateless protocol. It means that it treats every request from the client to server as a new request without pertaining the progress of the user across the web application. So we need sessions to recognise that the user is a part of our web application and it is done by storing user information in sessions. It just recognises your computer over the internet.

Why can’t we use cookies?
Cookies are used for storing information but on the client side. Cookies are less secure as cookie data can be easily readable as compared to sessions. Also, more data can be stored in sessions, and it expires when a user closes the browser. On the other hand, cookies that are independent of browser closing, persist data over a long duration of time.

How session works?
Sessions are stored in two sections
• Client-side session cookie
• Server side data

Client side cookie is just a reference to the server-side store data. When a is initiated using session start (), then it will check whether any session cookie data is sent from the user browser to server side. If yes, then it will return stored data and if not, then it will store data in a file on the server side and returns a reference to that stored data to the client side, that reference is termed as PHPSESSID.

It sounds very easy, and it works perfectly fine over a small application but when a web application starts using multiple servers and it goes scalable then problem starts..HOW?? Let’s see… Suppose I have 3 servers across different locations. When web application data comes from all the servers, now if session data stores only at one server as files, then when user try to access other server data, then problem arises as no reference ID is there to confirm that it’s a valid user since data is stored only at one server.

In the above-mentioned case, it’s better to use a database for storing user session data instead of files so that it can serve across multiple servers.
All in all, sessions play an important role in web applications so use it securely and wisely to enhance the user experience.

Tushar is a talented web developer and plays a major hand in developing Local RankWatch.

Exit mobile version