HomePHP Page 7 - Configuration Manipulation With PHP Config
Changing Things Around - PHP
Tired of writing (and rewriting) code to manage your application's configuration variables? Take a look at the PEAR Config class, a PHP toolkit designed specifically for manipulating configuration files and the data within them. This article demonstrates using the Config class to read and write configuration files in XML, PHP and INI formats, and use built-in methods to easily build Web-based application configuration modules.
Just as you can getContent(), you can also setContent() - and this next example demonstrates how, by using this method to change a configuration variable read from a file.
<?php
// include class
include("Config.php");
// instantiate object
$c = new Config();
// read configuration data and get reference to root
$root =& $c->parseConfig("mail.ini", "IniFile");
// get reference to [Settings] section of file
$settingsSection =& $root->getItem("section", "Settings");
// get POP account
$popAccountDirective =& $settingsSection->getItem("directive",
"POPAccount"); $popAccountDirective->setContent("my.new.email.address");
// write configuration back to file
$c->writeConfig();
?>
In this case, the setContent() method is used to change the value of a configuration variable, and then the writeConfig() method is used to write the entire set of variables back to the file.
This is one of the more common applications of the Config class - displaying the current configuration to the user, and saving modifications back - so pay attention to this next example, which builds on what you've just learned to create a script accepting user input for application configuration. This script is divided into two parts: a form which displays the current configuration (if available) and allows the user to edit it, and a form processor, which accepts the new configuration and saves it to a file.
<html>
<head>
</head>
<body>
<?php
if (!file_exists("ppp.conf"))
{
echo "Configuration not found!";
}
else
{
// form not yet submitted
if (!$_POST['submit'])
{
// prefill form with values from file
?>
<h2>Configuration</h2>
<table border="0" cellspacing="5" cellpadding="5">
<form action="<?=$_SERVER['PHP_SELF']?>" method="post">
// set new values from form input
$numberDirective->setContent($_POST['number']);
$retriesDirective->setContent($_POST['retries']);
$deviceDirective->setContent($_POST['device']);
$connect_scriptDirective->setContent($_POST['script']);
$ppp_userDirective->setContent($_POST['user']);
$ppp_passDirective->setContent($_POST['pass']);