December 22, 2011 learn_php

Sessions in PHP

Sessions in PHP

Before jumping right into sessions in PHP, we should take a look at what exactly is a session. Since we will talk about sessions in PHP, then we are certainly speaking of a website, some sort of communication with a client and server connection, and even a user interaction. So a session could be seen as, an established communication between a user, and a website, and this communication can be logged, monitored etc. This communication is between an elapsed time of existance. Once this communication is broken, the session may also die with it. Notice I said “may also”, since this is not the case if we are talking about a shopping cart, which can last a nice amount of time before the session is broken. In short, we can say, this is a direct conversation or meeting in between two or more communication devices, that share a unique id for security purposes and only devices with that unique id, can have access to what is being served(from the server or so).

You might ask yourself, why do sessions exists? The answer is very simple. Within a website, we have what we all know as HTTP. This protocol has no state, meaning, it has no built-in way to share any information in bewteen a page, unless it is sent via URL. Technically, HTTP has no way of knowing if a request came from the same user or not. Sessions were built for this purpose, to maintain a better user interaction, and display information accordingly, depending on what type of user it is.

Sessions in PHP are driven by a unique Session ID. This ID is automatically generated(random) by PHP itself. This ID can be stored within the client machine, or it can be passed on from page to page using the URL. On my opinion, I wouldn’t recommend anyone to send sensitive data through a URL. Besides, Sessions exists with that purpose, to be able to have a ‘session’ within a visit, to be able to isolate the user, so we will use our global PHP variable, which indeed is called ‘$_SESSION’. This variable was introduced into PHP in version 4.1.0. This same variable is the one responsible that deprecated $HTTP_SESSION_VARS.

How to connect a session variable with user

The session id, which has been mentioned earlier, can be seen as a key. This key allows you to create session variables. The information that is within this variable is stored at server level. This session id can be visible within a URL(which I would not recommend) or through a cookie. Now what in the world is a cookie? Do I look like a cookie monster?

Cookies, Yum!

At a certain point in my life, I was reading a magazine, in which talked about these cookies. By then, I had no idea what they were. Making the story short, they described these cookies as being malicious and unwanted. The fact is, these cookies actually somewhat helpful, as long as no privacy is breached. These help you as a web develpor, to create those “Remember me” checkboxes in the websites.

These cookies can be created by sending a header with the following format:

This will create a cookie with the name of MYNAME. All other parameters are optional. If no date is passed on, then it will assume that this will last for ever and ever! This cookie will need to be deleted manually by either you as the programmer, or manually by the user in his/her machine. This cookie will be sent to the server, once there is a connection established between the users machine, and the server that issued the cookie.

Cookies can also be set within PHP. Let’s take a look at how this is done. Please note the similarity between sending in a header, and using setcookie() from PHP.

The parameter name is also required in this setcookie function. All others are optional, just like sending in an HTTP header. Let’s setup a quick cookie for this site:

This cookie can now be accessed via the cookie superglobal, $_COOKIE[‘JOTORRESCOOKIE’]. If you need to delete this same cookie, you would call this same cookie with the same function, setcookie, sending the same name, and making the expiry date to a date in the past.

Let’s get to the fun part. Let’s use cookies with the session variables.
When using coookies with PHP, it is not necessary to create the cookie manually, as the session functions already do that for you. Just in case you would like to do it on your own, here is the way:

How to implement a session

In the past, PHP had used session_register() function to register any session variable you wanted to create. This has been deprecated as of PHP 5.3.0. If you have the latest version, you will not need to use this function. If you were to have an older version, then yes you can use this function, but I would just recommend getting an upgraded version of PHP. Now days, it’s simpler, if you need a session registered, all you need is:

This session variable will be available throught the whole user visit. If you browse from one page to the next, and need to verify if there is a session set, you would need to place the session_start on that page too. It is highly recommended to place session_start() at the very top of your script. Having this function call at the top will not affect the way the sessions have been registered. For example, if in page 1 you started a new session, and travel to page 2. Both pages should have session_start() at the very top. This function will automatically check if there has been a session started already. If so, then it will take the session variables and pass them on. If not, then it will start a new session for the user. To use the session variable, it is like any other PHP variable, but you should always check if the session variable has been declared(set) before using.

If you fail to check for registered session variables, you will get an undeclared variable error at the least.

Unset Sessions – Destroy Sessions

There comes a time in which the session is no longer needed. To do this you simply call unset to manually unset a specific session. Here’s how:

Note: If you try to unset the whole session variable, it may cause problems. To avoid these problems, you can easily blank out the current session like this:

This previous example will wipe out the whole array, making it an empty session, with no session variables in it. Once you are done using a session, you should unset the session using any of the paths described above, then you can destroy the session with a simple function called ‘session_destroy.

The above will clean up the unique session id that has been given to this session by PHP.

Let’s build 3 pages to use the sessions. The first page we will identify the username, and create a session with that username on the second page. The second page can only be seen if the username was submitted through the first page. The third page we will make it say goodbye username, and destroy the session. This third page will be visible only if the session has been made on the second page.

Lets begin.

Filename: index.php

Page 2
Filename: members.php

Page 3
Filename goodbye.php

This previous example is absolutely simple, and may not serve your hunger for session variables, but my next post about sessions will talk about sessions and mysql database. This way, you can login a user, and be able to display content accrodingly.

Hope you all enjoyed!

2 thoughts on “Sessions in PHP

Leave a Reply

Your email address will not be published. Required fields are marked *

The qTranslate Editor has disabled itself because it hasn't been tested with your Wordpress version yet. This is done to prevent Wordpress from malfunctioning. You can reenable it by clicking here (may cause data loss! Use at own risk!). To remove this message permanently, please update qTranslate to the corresponding version.