Coder Perfect

Using PHP to create a configuration file

Problem

I’d like to make a config file for my PHP project, but I’m not sure how to go about it.

So far, I’ve come up with three concepts.

1-Use Variable

$config['hostname'] = "localhost";
$config['dbuser'] = "dbuser";
$config['dbpassword'] = "dbpassword";
$config['dbname'] = "dbname";
$config['sitetitle'] = "sitetitle";

2-Use Const

define('DB_NAME', 'test');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');
define('TITLE', 'sitetitle');

3-Use Database

I’ll be using the configuration in classes, so I’m not sure which method is ideal or if there is a better one.

Asked by Ali Akbar Azizi

Solution #1

One basic but elegant solution is to create a config.php (or whatever name you choose to call it) file that simply returns an array:

<?php

return array(
    'host' => 'localhost',
    'username' => 'root',
);

And then:

$configs = include('config.php');

Answered by Hugo Mota

Solution #2

A versatile and powerful solution is to use an INI file! PHP contains a built-in function to take care of it. For example, you could make an INI file that looks like this:

app.ini

[database]
db_name     = mydatabase
db_user     = myuser
db_password = mypassword

[application]

app_email = mailer@myapp.com app_url = myapp.com

So all you have to do now is dial the following number:

$ini = parse_ini_file('app.ini');

The $ini array may then be used to quickly access the definitions.

echo $ini['db_name'];     // mydatabase
echo $ini['db_user'];     // myuser
echo $ini['db_password']; // mypassword
echo $ini['app_email'];   // mailer@myapp.com

IMPORTANT: The INI file must be kept in a non-public folder for security reasons.

Answered by Marcio Mazzucato

Solution #3

I’ve modified @hugo leonardo’s solution slightly:

<?php

return (object) array(
    'host' => 'localhost',
    'username' => 'root',
    'pass' => 'password',
    'database' => 'db'
);

?>

When you include the php: $configs->host instead of $configs[‘host’], you can use the object syntax.

You can also have this config.php file contain all your configs if your app has client-side configs (like an Angular app) (centralized in one file instead of one for JavaScript and one for PHP). The trick would therefore be to have a separate PHP file that only echoed client-side information (to avoid displaying anything you don’t want to display, such as the database connection string). Call it something like get app info.php:

<?php

    $configs = include('config.php');
    echo json_encode($configs->app_info);

?>

The following assumes you have an app info parameter in your config.php file:

<?php

return (object) array(
    'host' => 'localhost',
    'username' => 'root',
    'pass' => 'password',
    'database' => 'db',
    'app_info' => array(
        'appName'=>"App Name",
        'appURL'=> "http://yourURL/#/"
    )
);

?>

So your database information stays on the server, but your app information can be accessed via JavaScript, for example with a $http.get(‘get app info.php’). The kind of call is then(…);

Answered by BoDeX

Solution #4

The options I see with relative merits / weaknesses are:

File based mechanisms

These need your code to look for the ini file in certain areas. This is a challenging issue to fix, and it occurs frequently in large PHP applications. However you will likely need to solve the problem in order to find the PHP code which gets incorporated / re-used at runtime.

The most common solutions are to always use relative directories or to search from the current directory upwards for a file designated exclusively in the application’s base directory.

PHP code, ini formatted files, JSON, XML, YAML, and serialized PHP are all common file formats for config files.

PHP code

This gives you a lot of versatility when it comes to encoding different data structures, and the parsed code will be available from the opcode cache (if it’s processed via include or need), so you’ll get a performance boost.

The include path function abstracts the file’s probable locations without requiring any further code.

Separating configuration from code, on the other side, is important for separating responsibilities. It gives you a way to insert more code into the runtime.

If the configuration is generated by a tool, the data in the tool may be validated, but there is no standard mechanism for escaping data for embedding into PHP code, as there is for HTML, URLs, MySQL statements, and shell commands….

Data that has been serialized This is relatively efficient for small amounts of configuration (up to around 200 items) and allows for use of any PHP data structure. It requires very little code to create/parse the data file (so you can instead expend your efforts on ensuring that the file is only written with appropriate authorization).

Content written to the file is automatically handled when it escapes.

Because you can serialize objects, you may use the __wakeup magic method to invoke code just by reading the configuration file.

Structured file

Storing it as an INI file, JSON, or XML, as Marcel suggests, gives a simple api to map the file into a PHP data structure (and, with the exception of XML, to escape the data and create the file), while avoiding the code invocation issue that serialized PHP data introduces.

It will perform similarly to serialized data in terms of performance.

Database storage

This is best used when you have a lot of configuration but just require a small bit for the current activity – I was astonished to find that retrieving data from a local MySQL instance was faster than unserializing a datafile with about 150 data items.

However, it’s not a suitable place to save the login credentials for your database!

The execution environment

In the PHP execution environment, you can change values.

This eliminates the need for the PHP code to look for the configuration in a specified location. However, it is difficult to update globally at runtime and does not scale well to vast volumes of data.

On the client

The client is one location I haven’t discussed for storing configuration info. Because of the high network cost, this does not scale well to huge quantities of configuration. And since the end user has control over the data it must be stored in a format where any tampering is detectable (i.e. with a cryptographic signature) and should not contain any information which is compromised by its disclosure (i.e. reversibly encrypted).

On the other hand, this provides a lot of advantages for storing sensitive information that belongs to the end user: if you don’t store it on the server, it can’t be stolen.

Directories of Networks DNS / LDAP is another interesting area to store configuration data. This will work for a small number of little pieces of information, but you don’t have to use the first normal form – consider SPF.

Caching, replication, and distribution are all supported by the infrastructure. As a result, it’s ideal for very big infrastructures.

Version Control systems

Configuration, like code, should be managed and version controlled, so pulling configuration from your VC system is a suitable option. However, because this sometimes comes at a large performance cost, caching may be recommended.

Answered by symcbean

Solution #5

Well – it would be sort of difficult to store your database configuration data in a database – don’t ya think?

But, truly, this is a highly subjective question because any style can work, and it’s all a matter of personal preference. Personally, I’d choose a configuration variable over constants because I don’t like things in the global space unless they’re really necessary. Except for my database connection logic, none of the functions in my codebase should be able to quickly access my database password, therefore I’d utilize it there and then likely erase it.

To respond to your comment, none of the parsing mechanisms (ini, json, etc) would be the fastest, but they’re also not the sections of your program that you’d need to focus on optimizing because the time difference on such little files would be minimal.

Answered by Colin M

Post is based on https://stackoverflow.com/questions/14752470/creating-a-config-file-in-php