Configuration File Processing with PHP - A Simple Configuration File
(Page 2 of 4 )
Probably the simplest form of a configuration file is a list of options and their corresponding values. An example of this type is the configuration file for a Linux kernel before it is compiled.
# ATA/IDE/MFM/RLL support # CONFIG_IDE=y
# # IDE, ATA and ATAPI Block devices # CONFIG_BLK_DEV_IDE=y CONFIG_BLK_DEV_IDEDISK=y CONFIG_BLK_DEV_IDECD=n |
Each line that starts with a hash is considered a comment and is disregarded by the script. Other lines list options and set their desired values. For example, the CONFIG_IDE option has been set to "y" and the CONFIG_BLK_DEV_IDECD has been set to "n."
PHP code designed to read such a configuration file might look like this:
<?php $config_file = "my_config.conf"; $comment = "#";
$fp = fopen($config_file, "r");
while (!feof($fp)) { $line = trim(fgets($fp)); if ($line && !ereg("^$comment", $line)) { $pieces = explode("=", $line); $option = trim($pieces[0]); $value = trim($pieces[1]); $config_values[$option] = $value; } } fclose($fp);
if ($config_values['CONFIG_IDE'] == "y") echo "CONFIG_IDE is set<br />""; else echo "CONFIG_IDE is not set<br />"; ?> |
In our example code, $config_file holds the name of the configuration file and $comment holds the character used to designate comment lines.
You'll notice how we trim the white space from our input several times. People like to format their configuration files with indents and other white spaces for the sake of readability and we would want to accommodate that.
After we obtain a line from the configuration file, we check to see if the line contains any data and if it does not start with our comment character. If it passes both of these tests then we assume it is a configuration directive.
Once we've established we have a configuration directive we break it up into it's two distinct pieces and store them in an array for future use. In the example I've used and array named $config_values, and the option itself acts as the key to the value's entry. The information from the configuration file can used throughout the script simply by referencing that array.
Next: A Grouped Configuration File >>
More Miscellaneous Articles
More By bluephoenix