Garg Garg - 1 month ago 7
PHP Question

Reading DB credentials in Laravel from files outside laravel core

Sorry if the question is trivial for someone but I wasn't be able to make it and to find answer so far. In

Laravel
we have DB credentials in
app/config/database.php


'connections' => array(
...

'mysql' => array(
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'myDB',
'username' => 'myUser',
'password' => 'myPass',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
),

...
),


Now I have 2 custom files one in
public
directory and one in
libraries
directory which also got db credentials in them

$servername = "localhost";
$username = "myUser";
$password = "myPass";
$dbname = "myDB";

$conn = new mysqli($servername, $username, $password, $dbname);


Is there a way somehow to include
app/config/database.php
in those files and read DB credentials from instead of have DB credentials in 3 files?

Answer

If test.php would live inside your public folder:

// test.php
$config = include __DIR__ . '/../app/config/database.php';
// var_dump($config);

$servername = $config['connections']['mysql']['host'];
$username   = $config['connections']['mysql']['username'];
$password   = $config['connections']['mysql']['password'];
$dbname     = $config['connections']['mysql']['database']; 

$conn = new mysqli($servername, $username, $password, $dbname);