Where to store database login credentials for a PHP application Where to store database login credentials for a PHP application database database

Where to store database login credentials for a PHP application


I use an .ini-file, which is then parsed via parse_ini_file(INI_FILENAME_HERE, true).This file isn't under version control (as are the php-/template-/whatever-files). So on every machine I create that file (.database.ini) for the respective database connection.

Example .ini-file for a MySQL-connection, using PDO:

[db_general]driver = "mysql"user = "USERNAME"password = "PASSWORD"; DSN; see http://www.php.net/manual/en/pdo.drivers.php[db_data_source_name]host = "localhost"port = 3306dbname = "DATABASE_NAME"; specify PDO-options, provide keys without PDO::; see http://www.php.net/manual/en/pdo.drivers.php[db_pdo_options]MYSQL_ATTR_INIT_COMMAND = "SET NAMES utf8"; specify more PDO-attributes, provide keys without PDO::; see http://php.net/manual/en/pdo.setattribute.php[db_pdo_attributes]ATTR_CASE = "PDO::CASE_LOWER"ATTR_ERRMODE = "PDO::ERRMODE_EXCEPTION"ATTR_EMULATE_PREPARES = false

Since one can't use :: within .ini-file-keys, use constant('PDO::' . $iniKey) in your code to get the desired PDO-constants.


I recently had to deal with this issue, and what I did was create two new database users. The first had no privileges at all, other than read privileges on tables in his own schema. The second had insert privileges to a "load" table I would be populating with my code.

The unprivileged user got a "credentials" table in his schema, which held the credentials and password of the insert user (along with some other parameters I needed for my app). So the code only contained the credentials for the unprivileged user, hard-coded and changed periodically, and at runtime it would look up the credentials it needed to do inserts. The lookup took place behind our firewall, between servers, so it wasn't something an outsider could eavesdrop on.

It wasn't developers I was worried about, it was outsiders and power users, who could theoretically gain access to the web server and peek at ini files. This way, only developers and DBAs could snoop (and we all know each other). Anyone else would have to figure out how to query the database, figure out what SQL to use, figure out how to run code... Not impossible, but certainly a gigantic multi-step pain in the butt and not worth it.

Pretty safe -- in theory, anyway...


Another approach would be to setup environment variables on the live and development machine and access them from the code... I don't know much php, but in python that would be:

import ospassword = os.environ('DB_PASS')

This lets you distribute accounts and passwords as needed to developers and deployed servers. Depending on their permissions on that machine, developers could be prevented from having any access to the live password.