PHP Configuration file class.

NardCake 2 Tallied Votes 955 Views Share

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!

LastMitch commented: Thanks for sharing! +9
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);
	}
}
pritaeas 2,194 ¯\_(ツ)_/¯ Moderator Featured Poster

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

NardCake 30 Posting Pro in Training

@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.

NardCake 30 Posting Pro in Training

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!

NardCake 30 Posting Pro in Training

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.

Member Avatar for diafol
diafol

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

Member Avatar for diafol
diafol

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.

NardCake 30 Posting Pro in Training

@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.

Member Avatar for diafol
diafol

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.

atef201080 0 Newbie Poster

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

NardCake 30 Posting Pro in Training

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

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

For parsing ini configuration files there is a parse_ini_file() function.
http://php.net/manual/en/function.parse-ini-file.php

That could simplify the class a bit.

Vitaly_1 15 Newbie Poster

PHP INI Read and Write Class: Read and write configuration values in INI files:
https://www.phpclasses.org/package/8119-PHP-Read-and-write-configuration-values-in-INI-files.html

P.S.
For php version 7.x, change the line in the class
function INI (){ on
public function __construct () {
so that there is no mistake:

Deprecated: Methods with the same name as their class will not be constructors in a future version of PHP; INI has a deprecated constructor in INI.class.php on line 79
rproffitt commented: I worry here. Are you going to work all 7+ YO discussions like this? (deprecation issues)? +15
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.