Garg Garg - 1 year ago 76
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

we have DB credentials in

'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
directory and one in
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
in those files and read DB credentials from instead of have DB credentials in 3 files?

Answer Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download