11

Where do you put the connection settings for a database connection (things like host, dbname, user, password)? Is it placed in the database class or file, or outside in a config file, or somewhere else?

Daryll Santos
  • 2,031
  • 3
  • 22
  • 40
  • It depends on your implementation... You can put to a settings file so you can customize whenever you want. or if you love OOP then you can use class also.. but probably used settings file. – Pratik Nov 11 '12 at 06:25
  • 2
    I usually put it in a file outside of web root, and then include it into whatever application I need it in. This makes it a bit more secure from being accidentally exposed to the web, and allows multiples applications to use the same settings where changing that one file will keep all apps db settings up to date. – kittycat Nov 11 '12 at 06:28

4 Answers4

5

Ideally, you should place it in a config file, which can be something as simple as a PHP array.

For example: db_config.php

$db_config = array(
  'host' => 'localhost',
  'user' => 'username',
  'password' => 'qwerty'
);

You should then place this file outside your document root for maximum security. This way, if your webhost fails you and begins serving PHP files as text files (happens), no one can get your DB credentials.

Ayush
  • 41,754
  • 51
  • 164
  • 239
3

It can be done in many ways, but what is common is to put it in a settings file, and keep that file outside of the webroot, so that information about the database password can not accidentally leak into the web.

Billy Moon
  • 57,113
  • 24
  • 136
  • 237
2

For PostgreSQL, I really like to use pg_service.conf. It allows me to put all connection specific settings (hostname, database name, username, password, etc) into ~/.pg_service.conf or to /etc/postgresql-common/pg_service.conf and give them common name (service name).

Now, any program (Perl, PHP, etc) that wants to connect to database can simply specify "service=name" as their connection string - nice, clean, secure and easily maintainable.

As far as I know, MySQL has similar mechanism for ~/my.cnf or /etc/my.cnf files - you may want to look into that.

mvp
  • 111,019
  • 13
  • 122
  • 148
1

There are a lot of ways doing it, but I do it this way by defining CONSTANTS:

Create a config/db.php

<?php
define('DB_INFO','mysql:host=localhost;dbname=test');
define('DB_USER','root');
define('DB_PASS','');