note 24172 added to ref.filesystem
| From: | christian dot gilissen at home dot nl | Date: | Thu, 08 Aug 2002 13:31:33 +0000 |
| Subject: | note 24172 added to ref.filesystem | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-34530@lists.php.net to get a copy of this message | ||
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. :)
--
http://www.php.net/manual/en/ref.filesystem.php
http://master.php.net/manage/user-notes.php?action=edit+24172
http://master.php.net/manage/user-notes.php?action=delete+24172
http://master.php.net/manage/user-notes.php?action=reject+24172