How can I avoid hardcoding the database connection password?

孤街醉人 提交于 2019-12-04 08:09:43

Ok, here's the one with the ini file:

xxx.php

<?php

    $db_params = parse_ini_file( dirname(__FILE__).'/db_params.ini', false );

    // .....

    $this->conn = new mysqli($db_params['host'], $db_params['user'], $db_params['password'], $db_params['dbname'], $db_params['port'], $db_params['socket']).mysqli_connect_error());

    // ...

?>

db_params.ini

host=mysql.example.com
port=3306
socket=
user=testuser
password=myPasswort
dbname=myDatabase

Use a single file to contain your configuration variables and exclude this file when sharing your code.

For example:

require_once('config.php');
$this->conn = new mysqli($config['db']['host'], $config['db']['user'], $config['db']['pass'], $config['db']['dbname']);

The config.php file would include:

$config['db']['username'] = 'user';
$config['db']['password'] = 'pass';
...

You could/should expand this to include the host, port, database name etc.

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