I recently developed some functions that are meant to manage global variables within a PHP script.
For example, let us assume you want your script to save some configuration variables from an execution to another.
You may want to do something like:
<?php
...
$config = get_my_script_saved_config_vars();
...
if (!empty($_POST['myVar']))
{
$config['myVar'] = $_POST['myVar'];
save_my_script_config_vars($config);
}
...
if (!empty($config['myVar']))
{
do_some_actions_using_config_var($config['myVar']);
}
...
?>
Often, when dealing with this sort global/persistent configuration variables, you have to use a database or a special file.
Now, simply include this code to your script:
<?php
/**
* Provides a simple way to manage local persistent variables.
*
* @author Enisseo <http://www.enisseo.net>
*/
class LocalConfig
{
/**
* Returns the current local configuration.
* @return mixed
*/
public static function load()
{
$file = LocalConfig::_findFile();
$config = array();
if (!empty($file))
{
$content = file_get_contents($file);
$result = array();
if (preg_match('#<\?php\s+/\*CONFIG:(.*?)ENDCONFIG\*/ \?>#i', $content, $result))
{
$configStr = trim($result[1]);
$config = @unserialize($configStr);
}
}
return $config;
}
/**
* Save the current local configuration.
* @param $config mixed
*/
public static function save($config)
{
$file = LocalConfig::_findFile();
if (!empty($file))
{
$content = file_get_contents($file);
$configStr = '<?php /*CONFIG: ' . @serialize($config) . ' ENDCONFIG*/ ?>';
$content = preg_replace('#(<\?php\s+/\*CONFIG:(.*?)ENDCONFIG\*/\s+\?>|^)#i', $configStr, $content);
file_put_contents($file, $content);
}
}
/**
* Returns the caller file.
* @return string
*/
private static function _findFile()
{
$trace = debug_backtrace();
for ($i = 0; $i < count($trace); $i++)
{
if ($trace[$i]['file'] != __FILE__)
{
return $trace[$i]['file'];
}
}
return null;
}
}
You can either copy and paste into your script or include a file containing this script. Then, you only have to use the two static functions:
<?php
include_once('LocalConfig.php');
$config = LocalConfig::load();
if (!empty($config['name']))
{
print_form_asking_for_name();
}
if (!empty($_POST['name']))
{
$config['name'] = $_POST['name'];
LocalConfig::save($config);
}
This way you do not have to worry about databases or config files in order to store and manage persistent variables: the variables are stored within the file, in the begining of the source code.
If you find any bug, please let me know.