Everyone has their own preferences. I prefer to store my database settings in .ini outside the web root, and then give it the value 0600 chmod so that someone other than the owner does not read it.
An .ini example would look like this:
[database] driver = mysql host = localhost ;port = 3306 schema = yourdbname username = dbusername password = some_pass
Then you can use the php parse_ini_file function, then in your constructor you just read this and parse it into an array:
public function __construct($file = 'dbsettings.ini') { // @todo: change this path to be consistent with outside your webroot $file = '../' . $file; if (!$settings = parse_ini_file($file, TRUE)) throw new exception('Unable to open ' . $file . '.'); $dns = $settings['database']['driver'] . ':host=' . $settings['database']['host'] . ((!empty($settings['database']['port'])) ? (';port=' . $settings['database']['port']) : '') . ';dbname=' . $settings['database']['schema']; // if not PDO, this part needs to be changed parent::__construct($dns, $settings['database']['username'], $settings['database']['password']); }
And alt, you have a simple and secure way to set up a database connection. This class was taken from the PDO extender class, so if you are not using PDO, you need to change this line, but as you can see, you get the username, etc. In the $settings array.
I would really like to avoid storing information about any type of database in a variable of type CONSTANT or GLOBAL . Thus, $settings is only available for this class function and nothing else, providing an extra bit of security level.
source share