1.11M Members

PHP Configuration file class.

 
2
 

Hello! I needed a configuration file for a application I'm working on so I first used the built in ini functions in php but it wasn't easy to write the ini files. So I wrote myself a class here to parse a configuration file and write/edit configuration files. I plan to write some other useful functions for it eventually but it's quite simple really so I thought I would share it. Hope it helps! Ok here is the class:

class config {
    //this function parses a config file
    public function parse_config($file){
        //fetch the contents of the specified file.
        $content = file_get_contents($file);
        //splits the content into an array by line break
        $lines = explode("\n",$content);
        //define a array to tag every property on.
        $array = array();
        //loops through the array/lines
        foreach ($lines as $value) {
            //if the first character of the line isn't a # (comment character) continue on, if it is it's just ignored.
            if(substr($value,0,1) != "#"){
                //Split the line at = to fetch the property name and value.
                $lineSplit = explode("=",$value);
                //define the property name
                $propName = $lineSplit[0];
                //define the property value
                $propValue = $lineSplit[1];
                //trim whitespace
                $propValue = substr($propValue,0,strlen($propValue)-1);
                //set the property in the array equal to it's value
                $array[$propName] = $propValue;
            }
        }
        return $array;
    }
    //this function writes or edits a config file
    //defining a var quickly
    public function edit_config($property,$equals,$file){
        //fetch content of the file
        $content = file_get_contents($file);
        //splits the content into an array by line break
        $lines = explode("\n",$content);
        //defines a array for new lines, throwing edited one in the mix
        $newLines = array();
        //counter
        $count = 0;
        //loops through the array/lines
        foreach($lines as $value) {
            //length of specified property name
            $propLength = strlen($property);
            //check if the beginning of line is equal to the property name
            if(substr($value,0,$propLength) == $property){
                //if it is add the new value to the new line array
                $newLines[$count] = "$property=$equals";
            }else {
                //if not just add the original line
                $newLines[$count] = $value;
            }
            //increment the count
            $count= $count+1;
        }
        $final;
        //loop through the newLines array, and append it to the final string with a line break
        foreach($newLines as $i){
        //is so extra lines arent added at top of file
            if(!isset($final)){
                $final = $i;
            }else {
                $final .= "\n".$i;
            }
        }
        //write the new file
        $write = fopen($file,"w");
        fwrite($write,$final);
        fclose($write);
    }
}

Basically the # character is the comment character, must be first space on the line for the line to be commented out. freely insert line breaks, they are all ignored in the configuration file. I will give you an example of how it works.
Here is a fake configuration file:

#This is a configuration file for some sort of web application!
#This thing does....
banner=this is banner text
#this does...
footer=this text goes in the footer
#All of those are examples

Ok now to parse that you would do this:

//create an instance of the class of course, include the file if you are in a different on as well obviously.
$class = new config();
//it can be any readable file extension really, I just chose cfg.
//set it to a variable since it outputs a array
$configs = $class->parse_config("thefile.cfg");
echo $configs['banner'];

That code will output this is banner text
Now to edit a config file you will do this:

//still with an instance of the class of course
$class = new config();

$configs = $class->edit_config("footer","a brand new footer","thefile.cfg");

Now some explanation. The first parameter is the property that will be changed. The second parameter is what the property will be changed to and the third of course is the file.
That code will output this to the file:

#This is a configuration file for some sort of web application!
#This thing does....
banner=this is banner text
#this does...
footer=a brand new footer
#All of those are examples

And yes comments and everything are preserved.
Thank you for reading!

class config {
	//this function parses a config file
	public function parse_config($file){
		//fetch the contents of the specified file.
		$content = file_get_contents($file);
		//splits the content into an array by line break
		$lines = explode("\n",$content);
		//define a array to tag every property on.
		$array = array();
		//loops through the array/lines
		foreach ($lines as $value) {
			//if the first character of the line isn't a # (comment character) continue on, if it is it's just ignored.
			if(substr($value,0,1) != "#"){
				//Split the line at = to fetch the property name and value.
				$lineSplit = explode("=",$value);
				//define the property name
				$propName = $lineSplit[0];
				//define the property value
				$propValue = $lineSplit[1];
				//trim whitespace
				$propValue = substr($propValue,0,strlen($propValue)-1);
				//set the property in the array equal to it's value
				$array[$propName] = $propValue;
			}
		}
		return $array;
	}
	//this function writes or edits a config file
	//defining a var quickly
	public function edit_config($property,$equals,$file){
		//fetch content of the file
		$content = file_get_contents($file);
		//splits the content into an array by line break
		$lines = explode("\n",$content);
		//defines a array for new lines, throwing edited one in the mix
		$newLines = array();
		//counter
		$count = 0;
		//loops through the array/lines
		foreach($lines as $value) {
			//length of specified property name
			$propLength = strlen($property);
			//check if the beginning of line is equal to the property name
			if(substr($value,0,$propLength) == $property){
				//if it is add the new value to the new line array
				$newLines[$count] = "$property=$equals";
			}else {
				//if not just add the original line
				$newLines[$count] = $value;
			}
			//increment the count
			$count= $count+1;
		}
		$final;
		//loop through the newLines array, and append it to the final string with a line break
		foreach($newLines as $i){
		//is so extra lines arent added at top of file
			if(!isset($final)){
				$final = $i;
			}else {
				$final .= "\n".$i;
			}
		}
		//write the new file
		$write = fopen($file,"w");
		fwrite($write,$final);
		fclose($write);
	}
}
 
0
 

If you use file instead of file_get_contents you'll get an array by default.

 
0
 

@pritaeas oic... I don't normally mess with files so I didn't know that, thanks for the info though! I will modify it because I imagine some more efficiency.
Also second code example line four, not quite sure I set that to a variable was rushing last night.

 
0
 

I actually found a bug in my system, the hard way I might add wasn't good and it took me as bit to reaslise what the problem was. Ok so basically replace the foreach loop in the edit_config function with this:

foreach($lines as $value) {
            //split the line to fetch the property name
            $lineSplit = explode("=",$value);
            //check if the beginning of line is equal to the property name
            if($lineSplit[0] == $property){
                //if it is add the new value to the new line array
                $newLines[$count] = "$property=$equals";
            }else {
                //if not just add the original line
                $newLines[$count] = $value;
            }
            //increment the count
            $count= $count+1;
        }

Basically if you would look what the system was before you might be able to see potential problems. So if you for example had a configuration file like this:

database_host=host
database_name=name
database_password=pw
database=database

And you edited the database property it would replace every one of those lines with the new database property line. I suggest if you are using this update that foreach loop as that could be devastating. Thanks!

 
0
 

Don't mean to spam but I can't edit my above post for some reason, anyways remove line 21 under the remove whitespace comment, it might be some bug with the comments, not quite sure but you could handle it there or afterwards.

 
0
 

Edit functions seem to be a problem on DW at this time. I believe Dani is on the case.

 
1
 

As you explode on '=', perhaps it's an idea to use trim() as you may have whitespace.
In addition, comments in ini files, tend to be led by ';'

You could go down the way of looking at parse_ini_file() function to read into a multidimensional array - this could be especially useful for sections, e.g. multi-step configuration following installation.

 
0
 

@diafol parse_ini_file is the only reason I wrote this, because there wasn't a built in write function so I decided it would be easier to write a whole class.

 
0
 

I understand that. If you don't mind getting rid of comments in the new file, you can use the the array from parse_ini_file() to overwrite the file.

 
0
 

why you don't just create a php config file like this ?
$database_host="host";
$database_name="name";
$database_password="pw";
$database="database";

 
0
 

Because it would be easier to write to it with an installation script/c-panel etc...

You
Post:
Start New Discussion
Tags Related to this Article