6.23 Creating Configuration Files


You are distributing files and you want to include a configuration file with which any user can work.

Technique

Use PHP's regular expression library to parse the file into an associative array:

 <?php $config_file = "program.conf"; $fp = @fopen($config_file, "r"); while ($line = @fgets ($fp, 1024)) {     $line = ereg_replace ("#.*$", "", $line);     list ($name, $value) = explode ('=', $line);     $name = trim ($name);     $value = trim ($value);     $config[$name] = $value; } ?> 

Comments

This script will parse a configuration file that looks like this:

 Name = Sterling Hughes Power = God #access to everything Super User Privileges = Yes 

where comments (a pound sign) are allowed. The file will then be loaded into an associative array in which the data on the left side of the equal sign is the key, and the data on the right side of the equal sign is the value. If you do not want to use an associative array, you can implement symbolic references, or "variable variables ," like so:

 <?php $config_file = "somefile.txt"; $fp = @fopen ($config_file, "r")   or die("Cannot open file $fn"); while ($line = @fgets ($fp, 1024)) {     $line = ereg_replace ("#.*$", "", $line);     list ($name, $value) = explode ('=', $line);     $name = trim ($name);     $value = trim ($value);     $$name = $value; } fclose($fp)   or die("Cannot close file $fn"); ?> 

Now, instead of accessing variables through an associative array, you can simply call the variable names . That is, if you have the configuration variable "ip_address" , you can access it simply by typing $ip_address.



PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net