Obtain database credentials from a txt

1

I'm doing a development in PHP that requires a database connection, currently the credentials are written in the code.

$server = '255.255.255.255';
$user   = 'user';
$pass   = '<kjdhsadflkjhseuhdfsejhsuhksad';
$db     = 'database';
$conn   = new mysqli( $server, $user, $pass, $db );

This method is common among developers, however it has been considered a highly dangerous practice.

A couple of weeks ago reviewing OS, I saw a user suggesting another collaborator to put those credentials out of the context of the script. Last year I reviewed a post from a developer who put his credentials in a .txt file and then pulled that information to his PHP script, however I do not remember the process.

I hope someone can give me some guidance on this topic.

    
asked by Alberto Siurob 22.10.2018 в 18:53
source

1 answer

0

I will raise two options.
There are several ways to get the contents of a .txt file.

A couple of examples:

$data=explode("\n", file_get_contents('data.txt'));

or

$data=file('data.txt', FILE_IGNORE_NEW_LINES);

Option 1

The file only contains the values of the connection.

File .txt

127.0.0.1
root
root
dbname

The variable $data would have an output ( var_dump ) similar to this:

array (size=4)
  0 => string '127.0.0.1' (length=9)
  1 => string 'root' (length=4)
  2 => string 'root' (length=4)
  3 => string 'dbname' (length=6)

We would only have to assign each element of the array to each variable.
It would be something like this:

$data=explode("\n", file_get_contents('data.txt'));
$host=$data[0];
$user=$data[1];
$pass=$data[2];
$db  =$data[3];
$conn=new mysqli($host, $user, $pass, $db);

Option 2

The file contains both the values of the connection and the name of the variables.

File .txt

host=127.0.0.1
user=root
pass=root
db=quiniela_test

The variable $data would have an output ( var_dump ) similar to this:

array (size=4)
  0 => string 'host=127.0.0.1' (length=14)
  1 => string 'user=root' (length=9)
  2 => string 'pass=root' (length=9)
  3 => string 'db=dbname' (length=9)

You just have to create a loop to sign the names of the variables automatically and their corresponding value. It would be something like this:

$data=explode("\n", file_get_contents('data.txt'));
foreach($data as $value) {
    $item      =explode('=', $value);
    ${$item[0]}=$item[1];
}
$conn=new mysqli($host, $user, $pass, $db);

If I did not make a mistake in writing it, the two options should work.

    
answered by 23.10.2018 в 11:21