Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I avoid hardcoding the database connection password?

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=... ?

like image 896
Kopse Avatar asked Feb 02 '16 15:02

Kopse


Video Answer


2 Answers

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
like image 191
hherger Avatar answered Oct 31 '22 16:10

hherger


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.

like image 20
Egg Avatar answered Oct 31 '22 14:10

Egg