How can I avoid hardcoding the database connection

2020-07-13 11:17发布

问题:

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.