Last active
September 17, 2020 13:58
-
-
Save thommyhh/bb354ee726f870baeca4778362e8c0dd to your computer and use it in GitHub Desktop.
PHP: Reading DB credentials from `.my.cnf`
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$dbConfig = [ | |
'host' => 'localhost', | |
'database' => '', | |
'user' => '', | |
'password' => '' | |
]; | |
if (file_exists($_SERVER['HOME'] . '/.my.cnf')) { | |
// If `.my.cnf` exists in PHP home directory, parse it with sections | |
$myCnf = parse_ini_file($_SERVER['HOME'] . '/.my.cnf', true); | |
foreach ($myCnf as $section => $config) { | |
if (in_array($section, ['client', 'mysql'])) { | |
foreach ($config as $name => $value) { | |
if (in_array($name, ['host', 'database', 'user', 'password'])) { | |
$dbConfig[$name] = $value; | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment