note 24172 deleted from ref.filesystem by spic

From: Date: Tue, 17 Sep 2002 09:03:38 +0000
Subject: note 24172 deleted from ref.filesystem by spic
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-36773@lists.php.net to get a copy of this message
[Editor's note: The simpler and faster equivalent to this set of functions is to use parse_ini_file(), and extract(), e.g. extract(parse_ini_file('myconf.cfg')). See the appropriate manual pages for more information] I wanted to use a configuration file for my PHP programs. But I wanted the code to do so to be easily adaptable. I came up with this code which uses variables to store variable names. ($$variable). It reads a known configuration file a puts all values into variables. We have a file like: ####################################### # comments mysql_password=mysql host=localhost # comments port=3306 database=guestbook user=mysql password=mysql ####################################### Now the PHP code to read these values from the file and attach them to the right variables. <? //put the variable names you want in an array. //these must be in the same order as in the file $var_names[0]="mysql_password"; $var_names[1]="host"; $var_names[2]="port"; $var_names[3]="database"; $var_names[4]="table"; $var_names[5]="user"; $var_names[6]="password"; //Open the configuration file for reading. $fp=fopen("file.conf", "r", 1); /* reset the array, so we can go through it. start reading the conf. file line by line. If a line starts with '#' or is empty, ignore it. If it's not, get the first variable name, and introduce a variable with the name we got out of the array, and give it a value of the line we read. We'll format it later on. now proceed with the next variable name. Doing it this way means variables in the file have to be in the same order as the ones in your array. */ reset($var_names); while (! feof($fp)) { $line=fgets($fp, 4096); if (($line!='') && ($line[0] !='#')) { $temp=current($var_names); $$temp=$line; next($var_names); } } //close the file fclose($fp); /* Now each variable looks like "variable = value", for instance echo "$port"; would show: port = 3086 just the line in your conf. file So lets format the variable and strip everything but the value. */ foreach ($var_names as $variable){ $pos=strpos($$variable, "$variable="); if (($pos === false) || ($pos!=0)){ echo "Error in guestbook.conf line"; echo $$variable; } else $$variable= trim(substr($$variable, strlen($variable)+1, strlen($$variable) - (strlen($variable)+1))); } ?> I realise some enhancements could be made, but in my opinion the really interesting part is about using variables to store variable names and then using them with $$variable. I hope it'll be of use to somebody. :)

« previous php.notes (#36773) next »