Seb1929
Seb1929

Reputation: 17

Is this a good enough way to "hide" the db credentials?

Just looking for some tips if this is good enough or if i should do anything different to "hide" my database credentials. Been searching for a long time. I have found alot of ways to do this and feel everyone does it a different way. So wondering if this is good enough. Thank you.

Right now I'm storing a config.ini file with my database credentials outside of the public directory. Then inside the public directory I got a folder name db_includes. This is where i have my db connection php file. This is the code for the database connection.

$config = parse_ini_file('../../private/config.ini');
$db = new \PDO('mysql:dbname='.$config['DB_NAME'].';host='.$config['DB_SERVER'].';charset=utf8mb4', ''.$config['DB_USERNAME'].'', ''.$config['DB_PWD'].'');

Also inside the db_includes folder i got a .htaccess file that has "deny from all" so its not possible to get to that db_includes folder or the database connection file.

Is this good or should i also move the database connection file outside of the public directory and just call it when i need it?

Upvotes: 1

Views: 452

Answers (1)

Elias Soares
Elias Soares

Reputation: 10264

There's a few ways of doing it. First, I recommend using a PHP file to store the credentials, this way if your htaccess fails, the php file will be parsed anyway and your credentials won't appear:

config.php:

<?php

return [
    "DB_NAME" => "database",
    "DB_USER" => "user"
    // ...
];

Wherever you need:

$config = require "path/to/config.php";
$db = new \PDO('mysql:dbname='.$config['DB_NAME'].';host='.$config['DB_SERVER'].';charset=utf8mb4', ''.$config['DB_USERNAME'].'', ''.$config['DB_PWD'].'');

If possible, keep it outside your public folder as it is a good way to make it safe.

Remember that if your database and server is well configured and safe enough you don't need to worry about database credentials.

Upvotes: 4

Related Questions