Introduction

In this tutorial I will try to explain and show you what sessions are and how to use them in PHP. Sessions are very powerful but also very dangerous tools the PHP developer has available to him while writing his sweet new PHP script. The danger of sessions is that one might end up putting all kinds of needless information in it ending up in either a very slow PHP application and or an application that just might show more information then one would like someone too.

Why Use Sessions in the first place?
To understand the need for sessions you must basically understand the architecture used by applications in general, and when you like to go in detail… The server client model that applies to most PHP applications. I wont like to go that length because its boring but I will point out the main difference that explains the basic need for sessions.

The Desktop application…
Is basically an infinite loop usually something like;
main{
}
that is constantly looking for certain triggers (system calls, interrupts, user input etc) before it will perform a certain declared task. It will run through the code over and over again till the application faces a declared trigger to respond on with an action.

The web application…
The web application is some kind of strange bird in the family. We are still working in somesort of an infinite loop as long as the remote browser is "browsing" our site. But it isn't as plain anymore as the main{} loop we had on our desktop application. In this case our loop is stopped when a result is being send to the remote browser. The loop continues when the remote user either selects a link or some javacode in the remote browser instructs us too.

In our program we simply run the code from rule 1 up to n# and we expect an result in the remote browser. If the result takes too long we will receive a timeout. If we refresh our browser we simply rerun the script and will expect the same results if we didn't insert some instructions somewhere on that page or address bar.

So… Simply put after running our first script we send some output to the remote browser containing the new instructions for our loop to continue. But when you are considering this (The script is reran every time an instruction is selected remotely ) there is allot of information loaded in memory during the initial script that we cant simply pass on the the remote browser and will be lost once it is finished. Now how do we save information that is still valid the next time the script is being run. Information like user information for instance, or our chopping cart while selecting more and more products on different pages?

What is a PHP Session

Exactly what the word claims to be. A session in which the user is continually browsing our application. So the from the time a remote user is opening our application up to the time he decides to close his browser, or visit a different site/application.

A session will be created automatically for each unique user that visits your site by default. On top of that you can instruct PHP to enable the SESSIONS on which PHP will do a couple of things. It will create a Session Identifier for tracking purposes, An Session Name, and a session file on the local hard drive. The file on the local hard drive will have the name equal to the Session ID that is generated by PHP when a session is started.

In this session you can store stuff you think you might need later on in your script (like user information or the chopping chart).

How does it look like in code?

Well the basics are very plain and simple actually. We start a session, store a string in the Session global, show a link on the page to a new page, and show the string we stored previously. Uhm.. It sounds rather complex but seeing the code might make it a bit more clear 😉

 
<?php
/* index1.php 
     because php needs to prepare some stuff in the background we need to tell it to start
    a session. It would be overhead if all that is being done while we don't use it in the end…*/
session_start(); 
 
/* The very important string we need in index2.php else our server will crash! */
$foo = 'bar';
/* We store the very important sting into the session array so it will be stored in the session */
$_SESSION['foo'] = $foo;
/* Show a link to the next page */
echo '<a href="index2.php">Goto Index2</a>';
?>
 

Oke now we have started a session, in it we saved our very important sting in a variable called $_SESSION (this is an PHP reserved name beware!). And a link that will send us to the new file that "should" show us our stored value… Oke lets put that to the test.

 
<?php
/* index2.php
/* We need to initialize the session again (load the session from file into memory ($_SESSION)) */
session_start();
/* Show our very important string so our server will not crash! */
echo $_SESSION['foo'];
?>
 

Some considerations to think over…

Oke… :S now you probably think… Nice! Now how can this be useful? And what was that "This might be dangerous" stuff all about?

Ow well I was kidding you not on that part. Remember the sessions are being stored to disk. There might be some problems with that. One is that a session file is human readable, meaning your readable string is just as readable in the session file. If I was to access your session files I might be able to gather important information about for instance mySQL connection data (if you stored it there). And use it to gain access to your precious database. (Yeah you need to hack to do that… ).

Also if you store to much in there and do that for a popular site you should consider that all that info is being managed, loaded, written, deleted from disk which is a pretty slow device in comparison to your memory.

Also using the session_start($id) you might be able to start in a different session then your own. And capture an active session that way. Nice things to think about while writing your site.

Also if someone closes its browser the session file inst immediately deleted. PHP isn't aware a user isn't connected anymore once it leaves. So once in a while the PHP garbage collector will destroy all leftover session information. But consider the fact that in the meanwhile the information is available!

So in most cases we will end up in writing a script to manage these sessions for your site and validate some stuff to handle this correctly and minimizing the risk involved.

Some simple things to check using sessions…

Here is an example of stuff you can check while using sessions.

User remote IP

 
function StartSession(){
       /* Check if we already started a session */
        if(!isset($_SESSION)){
                    session_start();
         }
 if(isset($_SESSION['remote_ip'])){
       if(!$_SESSION['remote_ip'] == $_SERVER['REMOTE_ADDR']){
             session_destroy();
             session_start();
             $_SESSION['remote_ip'] = $_SERVER['REMOTE_ADDR'];
      }
} else{
      $_SESSION['remote_ip'] = $_SERVER['REMOTE_ADDR'];
}
}      
 

The same you can do using all kinds of smart stuff like session_id() session_name(). But you might also use a database to store this kind of information and simply store a row identifier that points to the correct db entry. You might also use cookies to do some validation and so on.

Basis is that the $_SESSION superglobal enables you to store information outside the running script and pick it up when ever you like, where ever you like as long as the start_session() is called once.

Conclusion

Sessions are a nice way to store important information required by your webapplication during the length a user is browing your site. You should only consider wisely what kind of information you are storing in these sessions. And should consider the fact that these values are being stored outside memory which can have a performance impact. Experiment with it and find out that this is only the surface of all the capabilities available to the programmer using Sessions.

-Regards

This page was published on It was last revised on

0

1 Comment

  • Votes
  • Oldest
  • Latest
Commented
Updated

Thanks!

add a comment
0