Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How do I use global application variables in PHP?

Retrieving Data

How do I use global application variables in PHP?

by  rycamor  Posted    (Edited  )
I have been hearing for over a year now from frustrated former ASP developers who wished there was a simple way to set global variables, such as ASP's global Application object. This is not the same as a session variable , which is only availabe to a single user, but variables available anywhere, which PHP can get/set depending on certain events or values.

Of course experienced PHP users know there are several ways to accomplish the same thing, such as shared memory, parsing text files, or even a database.

But PHP does not wrap this up into a nice simple class with a couple of methods. This seems like a reasonable thing to want, so I have made a small "starter" class that allows for this, and could be extended in a few ways. For now it only writes to temp files, but anyone with a little work could get it to work with a database or shared memory. I have made this very simple, so it can be called with full object instantiation, or simply with a "class::method()" call:
Code:
<?php

/* filename: class.Application.php        *
 * Application class, includes methods to *
 * get set application variables by       *
 * storing serialized values to tempfiles */

class Application
{
 function setVar($varname,$value)
  {
    //$temp_path = 'C:\TEMP\'; // for Windows server
    $temp_path = '/tmp/';      // for Unix server
    $strvalue = serialize($value);
    // generate a storeable representation of
    // the value, with it's type and structure
    $file_pointer = fopen($temp_path . $varname, 'w');
    if(!(fwrite($file_pointer,$strvalue)))
    {
       return false;  //success
    }
       else
    {
       return true;   //not able to write file
    }
  } //end function setVar

 function getVar($varname)
 {
    //$temp_path = 'C:\TEMP\'; // for Windows server
    $temp_path = '/tmp/';      // for Unix server
    // file(path) returns an array, so we implode it
    if(!($strvalue = implode("",file($temp_path . $varname))))
     {
        return false; //could not get file
     }
     else
     {
        $value =  unserialize($strvalue);
        return $value;  //here's the value of the variable
     }
  } //end function getVar
} //end class Application
?>

Example 1 -- setting an application variable:

Code:
<?php

require_once("class.Application.php");

$myvariable = "Here is a test application variable."

if(!(Application::setVar("myvariable",$myvariable))){
 echo "Couldn't set variable!!";
}

else{
echo "Variable has been set!!";
}

?>

Example 2 -- retrieving an application variable:

Code:
<?php

require_once("class.Application.php");
if(!($appvariable = Application::getVar("myvariable"))){
 echo "Could not retrieve variable";
}

else{
 echo $appvariable;
}

?>

NOTE: since this at a very basic level at the moment, it does not take into account a few things to consider, such as where you decide to save your tempfiles. I recommend you set a non-standard directory, to avoid getting your files accidentally overwritten by other processes. Also, there is a security issue, if this is on a shared server, because others could read your tempfiles (unless this is on a system running PHP as a CGI, or PHP module in "safe mode", with your tempfiles in your own directory tree). Of course, you could use some sort of encryption scheme if security is really important.

Also, with a little work, this class could be extended to check for all existing set application variables in a directory, getting and setting expiry times for these variables, etc... For ideas on how to do that, just check out PHP's filesystem functions: www.php.net/filesystem

For those of you PHP'ers who are wondering what we are talking about, here is an example:

Let's say we have members-oriented website, where people are continually logging in, and performing whatever functions. Now, we want to set the site up so that anytime someone logs in, they receive a message announcing who was the last person to log in.

Normally, in PHP we would do that by saving logins to a table, and every time there is a new login, we read the login table, using date/time criteria to select the previous login information. For a large website, this can be an unnecessary overhead.

Instead, we could just set a certain variable every time someone logs in. User "Fred" logs in, so in PHP, we first run the class method Application::getVar("lastlogin"); This tells us who the most recently logged in visitor is. Then, we run Application:setVar("lastlogin", "Fred"), to update that variable to "Fred" who is now the most recent. Meanwhile, other users browsing the website, will see the most recent login at the top of the page. "User Fred just logged in", because we are retrieving that variable at the top of every page.

Using this method, we can get or set as many variables as we want, which can be seen accross the whole application, and we can do this without the fuss of inserting and querying a database.

Now, to expand on the above concept, we could actually set up the variable to be an array of users, and -- using the array_push method, we could just keep adding each new user to the end of the array. Now we have an array of all the currently logged-in users, with the most recent being at the end of the array. This could provide a nice way to manipulate interactions between users in a system.

class.Application is simply an easy syntax for setting values on an application level, without having to think about the mechanics. The next step is to set this up so it works with shared memory. Stay tuned .
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top