note 58368 deleted from function.file by bjori
| From: | bjori@php.net | Date: | Wed, 22 Mar 2006 13:46:24 +0000 |
| Subject: | note 58368 deleted from function.file by bjori | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-106248@lists.php.net to get a copy of this message | ||
Note Submitter: com dot gmail at trucex [reverse order]
----
I used the config file reader written by mvanbeek at supporting-role dot co dot uk for one of my own
scripts. I have made some modifications, and turned it into a class.
<?
class config_reader {
var $filename;
var $databaseHost;
var $databaseName;
var $databaseUser;
var $databasePassword;
function config_reader () {
$this->filename = './settings.conf';
$this->getSettings();
}
function getSettings () {
$config = file($this->filename);
reset($config);
foreach ($config as $line) {
$line = rtrim($line); # Get rid of newline characters
$line = ltrim($line); # Get rid of any leading spaces
if ($line == "" || $line == "\n" || strstr($line,"#") == 1) {
next($config);
} else {
list($key, $value) = preg_split("/\s*=\s*/", $line, 2); # split by "="
and removing blank space either side of it.
$this->$key = $value;
}
}
}
}
?>
Changes:
- I have cleaned up the layout of the code for readability and faster execution.
- I have moved the rtrim and ltrim functions to execute before the line check, to make sure the
line wasn't just a space, or a comment after a space.
- I changed strstr($line, "#") to strstr($line, "#") == 1 to make sure that
lines with a comment after the values are not left behind.
- I also changed the way preg_split assigns the results, primarily to clean up the code.
- I changed the way values are assigned to the variables. For me, this works better because I only
needed to get the database information from the user. If you would like a dynamic listing of
variables, do the following:
Remove the following lines:
<?
var $databaseHost;
var $databaseName;
var $databaseUser;
var $databasePassword;
?>
Add this line: (commented lines are only to provide location for new line)
<?
#class config_reader {
#var $filename;
var $settings; #ADD THIS LINE
?>
Then change this line:
<?
$this->$key = $value;
?>
to this:
<?
$this->settings[$key] = $value;
?>
NOTE: This has not actually been executed, so their might be a small error. I don't recommend
use of this script by those new to PHP, as you will need an understanding of file permissions and
setting the variables in classes.