Sessions in PHP

We have earlier gone through what a cookie is and had explored a lot on its usage in PHP.

So lets start understanding how do sessions in PHP work, while comparing a Cookie and a Session on our way ahead. As for now, lets assume that a session serves the same purpose as does a cookie.

Sessions are often used as an alternative to Cookies and is considered to be more efficient and safer than Cookies.

How do sessions work?

If you could recall, in case of cookies, the needed data is set into a sort of text file which is stored in some browser directory in the hard disk. However in Sessions, the needed data is set into a sort of text file exactly as in case of cookies, but the file holding these session data is kept safe on the server. So instead of exchanging whole set of data for every request to the server as in case of cookies, sessions just interact with the server through a unique session id. This unique session id maps to the respective session file on the server, which holds all the data specific to the user.

So coming back, how exactly does a PHP session work?

Okay, so here it goes! When we start a PHP session, PHP generates a unique id for the user and creates a file on the server named as sess_<unique generated id>. As a response to the client, the server asks the client browser to create a cookie named PHPSESSID with the value same as the generated unique ID. All the subsequent request carries the PHPSESSID cookie to the server, which helps in identifying the session file on the server. Once the session file is identified, all the session file entries are available to PHP and can be accessed through $_SESSION. We can now say that all the session variables we create for the user, the entry goes into the corresponding session file on the server.

Starting a session

Set session variables

Get session values

Remove all session variables

Destroying a session

Receive our updates to your inbox

Get more stuff like this
in your inbox

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.