TUTORIAL: Sessions and Background

  • may
  • Proficient
  • Proficient
  • User avatar
  • Posts: 328
  • Loc: Holland [NL]

Post 3+ Months Ago

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 Code: [ Select ]
 
<?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>;
?>
 
  1.  
  2. <?php
  3. /* index1.php
  4.      because php needs to prepare some stuff in the background we need to tell it to start
  5.     a session. It would be overhead if all that is being done while we don’t use it in the end…*/
  6. session_start();
  7.  
  8. /* The very important string we need in index2.php else our server will crash! */
  9. $foo = ‘bar’;
  10. /* We store the very important sting into the session array so it will be stored in the session */
  11. $_SESSION[‘foo’] = $foo;
  12. /* Show a link to the next page */
  13. echo<a href=”index2.php”>Goto Index2</a>;
  14. ?>
  15.  


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 Code: [ Select ]
 
<?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’];
?>
 
  1.  
  2. <?php
  3. /* index2.php
  4. /* We need to initialize the session again (load the session from file into memory ($_SESSION)) */
  5. session_start();
  6. /* Show our very important string so our server will not crash! */
  7. echo $_SESSION[‘foo’];
  8. ?>
  9.  


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
PHP Code: [ Select ]
 
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’];
}
}      
 
  1.  
  2. function StartSession(){
  3.        /* Check if we already started a session */
  4.         if(!isset($_SESSION)){
  5.                     session_start();
  6.          }
  7.  if(isset($_SESSION[‘remote_ip’])){
  8.        if(!$_SESSION[‘remote_ip’] == $_SERVER[‘REMOTE_ADDR’]){
  9.              session_destroy();
  10.              session_start();
  11.              $_SESSION[‘remote_ip’] = $_SERVER[‘REMOTE_ADDR’];
  12.       }
  13. } else{
  14.       $_SESSION[‘remote_ip’] = $_SERVER[‘REMOTE_ADDR’];
  15. }
  16. }      
  17.  


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
  • Anonymous
  • Bot
  • No Avatar
  • Posts: ?
  • Loc: Ozzuland
  • Status: Online

Post 3+ Months Ago

  • cristian
  • Born
  • Born
  • cristian
  • Posts: 1

Post 3+ Months Ago

Thanks!

Post Information

  • Total Posts in this topic: 2 posts
  • Moderator: Tutorial Writers
  • Users browsing this forum: No registered users and 4 guests
  • You cannot post new topics in this forum
  • You cannot reply to topics in this forum
  • You cannot edit your posts in this forum
  • You cannot delete your posts in this forum
  • You cannot post attachments in this forum
 
cron
 

© 1998-2014. Ozzu® is a registered trademark of Unmelted, LLC.