0

By default in CI4 we put the database connection values like hostname, username and password directly inside the Database.php

Example:

$default = [
        'DSN'      => '',
        'hostname' => 'localhost',
        'username' => 'adm',
        'password' => 'password',
        'database' => 'mydatabase',
        'DBDriver' => 'sqlsrv',
        'DBPrefix' => '',
        'pConnect' => false,
        'DBDebug'  => false,
        'charset'  => 'utf8',
        'DBCollat' => 'utf8_general_ci',
        'swapPre'  => '',
        'encrypt'  => false,
        'compress' => false,
        'strictOn' => false,
        'failover' => [],
        'port'     => 3306,
    ];

These values are kind of sensitive and attackers might able to obtain it if they somehow get the source code.

I try to declare a variable which value is passed in from other place and set it for the database connection value, but it seems like the configuration just allow string type.

So is there a way that we can get rid of using the hard-coded values inside this configuration? Or using any encryption method here?

1 Answers1

-1

An Option is - You can use a .env file to get the hardcoded value out of it. Check Dotenv File

Example

DB_HOSTNAME=localhost
DB_USERNAME=myusername
DB_PASSWORD=mypassword
....

In code

$default = [
    'hostname' => getenv('DB_HOSTNAME'),
    'username' => getenv('DB_USERNAME'),
    'password' => getenv('DB_PASSWORD'),
     ....
];
Abdulla Nilam
  • 36,589
  • 17
  • 64
  • 85
  • 1
    So instead of storing passwords in a PHP file, that at least cannot be read through HTTP request, you propose to put it in a plain text file with a well-known name. Great idea – Your Common Sense Jul 26 '23 at 06:50
  • You should do exactly what the answer suggested. Check the link, so you have a better understanding, what is .env file used for. Don't worry, it is placed outside of your document root, so it won't be visible to anyone except your app. – Dusan Aug 06 '23 at 19:06