Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load website configuration from JSON or PHP file?

Tags:

json

php

I've stored some website configuration data in a config.json file, with things like database connection parameters and routes. Something like this:

{
    "production" : { ... },
    "test" : { ... },
    "development" : { ... }
}

And the content is loaded with:

$config = json_decode(file_get_contents('config'), true);

However, inspecting some frameworks, I see direct usage of PHP scripts for configuration storage:

<?php
return array(
    'production' => array( ... ),
    'test' => array( ... ),
    'development' => array( ... )
);
<?php $config = (require 'config.php');

Which approach is the best?

like image 277
Tasso Evangelista Avatar asked Jul 16 '13 01:07

Tasso Evangelista


3 Answers

There are several advantages to using the config.php approach:

  1. The PHP compiler will tell you quickly if you have a syntax error in the config.php file when it gets loaded, whereas you would have to wait until you parse the JSON file to pick up any errors
  2. The PHP file will load faster than parsing the JSON file for the 2nd and subsequent page loads because the script will be cached by the web server (if cacheing is supported & enabled).
  3. There is less chance of security breach. As Michael Berkowski pointed out in his comment, if you don't store your JSON file outside the document root or configure the web server settings properly, web clients will be able to download your JSON file and get your database username & password and gain direct access to your database. By contrast, if the web server is configured properly to process *.php files via the PHP script engine, a client cannot directly download config.php even if it resides under the document root directory.

Not sure there are really any advantages to using JSON rather than config.php other than if you had multiple applications written in different languages (perl, python, and php for example) that all needed access to the same shared configuration information. There may be other advantages to JSON, but none come to mind at the moment.

like image 180
linguanerd Avatar answered Sep 17 '22 11:09

linguanerd


It is generally faster to load from a PHP config file, plus it also supports more features, such as closures and byte code caching (if enabled).

like image 21
Petah Avatar answered Sep 17 '22 11:09

Petah


Just a note - PHP has a special function for fast loading .ini files that can parse your configuration file

as mentioned in : PHP parse_ini_file() performance?

it is one of the faster method to load configuration files.

Here is the man for it:

http://php.net/manual/en/function.parse-ini-file.php

like image 40
azngunit81 Avatar answered Sep 19 '22 11:09

azngunit81