Load website configuration from JSON or PHP file?

I saved some site configuration data in a config.json file with parameters such as database connection parameters and routes. Something like that:

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

And the content is loading:

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

However, checking out some frameworks, I see direct use of PHP scripts to store the configuration:

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

Which approach is best?

+6
source share
3 answers

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

  • The PHP compiler will quickly tell you if you have a syntax error in the config.php file when it loads, while you have to wait while you parse the JSON file to get any errors.
  • The PHP file will load faster than parsing the JSON file to load the second and next page, since the script will be cached by the web server (if caching is supported and enabled).
  • There is less chance of a security breach. As noted by Michael Berkowski in his comment, if you do not 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 and password and get direct access to your database. In contrast, if the web server is correctly configured to process * .php files using a PHP script, the client cannot directly load config.php, even if it is located in the root directory of the document.

Not sure if there really are any advantages to using JSON and not to config.php, except if you had several applications written in different languages ​​(e.g. perl, python and php) that they all needed access to the same general configuration information. There may be other advantages to JSON, but at the moment no one comes to mind.

+12
source

As a rule, it loads faster from the PHP configuration file and also supports more functions, such as closing and caching code (if enabled).

+2
source

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

as stated in: php parse_ini_file () performance

This is one of the faster ways to load configuration files.

Here is this man:

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

+2
source

Source: https://habr.com/ru/post/949510/


All Articles