Reputation: 2081
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?
Upvotes: 12
Views: 6717
Reputation: 116317
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.
Upvotes: 2
Reputation:
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','');
Upvotes: 1
Reputation: 42450
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.
Upvotes: 5
Reputation: 58601
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.
Upvotes: 3