The Schworak Site | Log In | Up One Level

Cross session variables that survive a reboot.

Some times you may need to communicate across sessions. Or perhaps you need a value to survive a server reboot. There are two basic ways to perform this, store your data in a database or store it in a file.

To make this work, we are going to create a read/write folder in the root of our web site. You can put the folder any place you like. If you don't want the variables to survive a reboot, you could even use the operating system's temp folder and the OS should clean up the files.

For this example we will assume the use of the folder "DiskVar" just off the website's root folder. You can then use three function to set, get and delete variables. The data gets stored as JSON strings. Here is the source for the functions.

function getDiskVar($var,$default="")
{
    $v=$default;
    $f=$_SERVER["DOCUMENT_ROOT"]."/DiskVar/".$var.".json";
    if(is_file($f))
    {
        $h=fopen($f,"r");
        if($h!==false)
        {
            if(flock($h,LOCK_SH))
            {
                $v=json_decode(fgets($h));
            }
            fclose($h);
        }
    }
    return($v);
}
   
function setDiskVar($var,$value)
{
    $f=$_SERVER["DOCUMENT_ROOT"]."/DiskVar/".$var.".json";
    $h=fopen($f,"w");
    if($h!==false)
    {
        if(flock($h,LOCK_EX))
        {
             fwrite($h,json_encode($value,
                        JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP));
        }
        fclose($h);
    }
}

function delDiskVar($var)
{
    $f=$_SERVER["DOCUMENT_ROOT"]."/DiskVar/".$var.".json";
    if(is_file($f)) unlink($f);
}

Comments

<< Beautiful PHP dump to use in place of var_dump or print_r
All content on this site is copyright ©2004-2021 and is not to be reproduced without prior permission.