Load website configuration from JSON or PHP file?
json, php
Solution
There are several advantages to using the config.php approach:
- 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
- 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).
- 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.
Problem
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?