Managing Application Settings in PHP

March 27, 2012 | By

There are multiple ways to save application settings/configurations in PHP. You can save them in INI, XML or PHP files as well as a database table. I prefer a combination of the latter two; saving the database connection details in a PHP file and the rest in a database table.

The advantage of using this approach over the others will be apparent when developing downloadable scripts, as updates will not need to modify a configuration file of an already setup script.

To start create a table containing 3 fields: auto increment ID, setting name and setting value:

The following function updates the value of a setting by supplying it with the setting name and the new value.

The GetSetting function returns 1 or more values depending on the parameter passed. You can pass a setting name in a string or multiple settings in an array of strings. The latter will save you multiple trips to the database to perform a task that requires more than 1 setting like sending an email which needs the email server, protocol and credentials.

Here is an example of using the GetSetting function to initialize an email object.

Please note, as Remo pointed out in his comment below, this code does not filter the values sent to SaveSetting(). To prevent SQL injection and XSS attacks please make sure you check the values before saving them and also after reading them using GetSetting().

That’s it. Hope you found the post useful, and feel free to comment and share tips.

Filed in: MySQL, PHP | Tags:

Comments (2)

  1. Remo

    Please please read about SQL injections! This code contains several security issues!

  2. @Remo, thank you for your comment. This code is meant for managing settings only. I know filtering of input or escaping output should be done whenever a page accepts input from users. But this depends on each setting’s expected values which will increase the code listed here significantly and the post will loose its focus. However, I’ll add a note reminding users to do so.