How can I avoid hardcoding the database connection password?

社会主义新天地 提交于 2019-12-21 17:42:54

问题


I am working on a school-project (writing a website) and I ran into the problem of providing the password for the connection to our database. Because of our Open-Source license we have to publish the sourcecode but that would mean that everyone could connect to the database and see tha data.

Currently our connection (a php file) looks like this:

$host="************";
$password="************";
$this->conn = new mysqli($host, $user, $password, $dbname).mysqli_connect_error());

Now my question is: how can i provide the password to connect to the database without needing to write $password=... ?


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/35156847/how-can-i-avoid-hardcoding-the-database-connection-password

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