Where to put database connection settings?

二次信任 提交于 2020-02-01 00:39: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?


回答1:


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.




回答2:


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.




回答3:


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','');



回答4:


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.



来源:https://stackoverflow.com/questions/13329063/where-to-put-database-connection-settings

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!