Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to store easily editable config data in PHP?

Tags:

What is the fastest way to store config data in PHP so that it is easily changeable (via PHP)? First I thought about having config.php file, but I can't edit it on fly with PHP, at least not very simply? Then I thought about having XML files, but parsing them for each HTTP request is overwhelming. So, I thought about INI files, but then I figured that INI files are restricted to int/string values. In the end, I have come to the conclusion that JSON encoded file is the best:

$config['database']['host'] = ...; $config['another']['something'] = ...; ... json_encode($config); 

Since JSON can store arrays, I can create quite complex configurations with it, and it parses faster than INI files.

My question: did I miss something or is there a better way to do this?

like image 732
Tower Avatar asked Jan 06 '10 19:01

Tower


People also ask

Should I store config in database?

It really depends on your application. Storing the settings in the database has several advantages: Security - users can easily alter settings in the file or overwrite the contents. For Distribution - the same settings can be updated and loaded onto any machines on the network.

Where is config php stored?

I usually place database settings on config. php and all the dynamic settings on a database. All settings that don't change much are usually good to be placed to config file.

What is the way to include the file config php?

Copy the below code to include the 'config. php' file and get a print the name of the database and username. include ( 'config. php' );


1 Answers

Serialize is a better option than JSON for storing PHP variables.

I like to use var_export for saving config file, and using include for loading config info. This makes it easy to save config data progmatically AND makes the data easy to read/write for a person as well:

config.php:

return array(  'var1'=> 'value1',  'var2'=> 'value2', ); 

test.php:

$config = include 'config.php'; $config['var2']= 'value3'; file_put_contents('config.php', '<?php return ' . var_export($config, true) . ';'); 

Updated config.php now contains the following:

return array(  'var1'=> 'value1',  'var2'=> 'value3', ); 
like image 58
leepowers Avatar answered Oct 12 '22 15:10

leepowers