Working With Session Variables In PHP – Part 1

I can remember when I was learning to program in PHP a few years ago, people talking about things called session variables and thinking that it all sounded a bit scary. What were these things that people kept saying were so useful, and what were they used for?

Whenever I looked anything up on the Internet to do with session variables, the opening statement was normally something about HTTP being a stateless protocol – so I was lost straight away. What was a stateless protocol when it was at home?

In this article I’m not going to use fancy technical terms to describe what session variables are and what they are used for, instead, I’m going to use plain English…or at least try to!

Let’s start at the beginning. If I launch my web browser and open the home page of a web site, and then, from that page, click on a link to open another page on the same web site, the web server that sent the first page to my computer does not care that it is me who has also asked for the second page. The web server simply ‘serves’ pages as they are requested by a web browser – it doesn’t keep track of who is requesting them.

In many cases this isn’t a problem, because it doesn’t matter that the web server doesn’t know that it was me (or rather the web browser running on my computer) who requested both pages. However, if the web site requires me to log on in order to open subsequent pages on the site, the web server does need to know that it is me who is requesting the second page.

Session variables enable a web server to keep track of a web site visitor as they navigate around the site. Otherwise, you would have to log on to each page on the site individually, which would be a bit of a drag to say the least.

Session variables are simply variables that last for the duration of a session. This enables the web server to assign my login name, for example, to a session variable called, say, ‘username’, and then to check the value inside that variable for all pages that require me to be logged on in order to access them.

What is a session? I can here you saying. A session is simply the time from when you start your web browser to when you close it. If you log on to a particular web site, and then navigate away from it to another site, you will (normally) still be logged onto the first site until you close the web browser. OK, there are other ways that might cause you to be logged off the first site, but in general, that’s the way it works.


Source link