Skip to content

Instantly share code, notes, and snippets.

@thommyhh
Last active September 17, 2020 13:58
Show Gist options
  • Save thommyhh/bb354ee726f870baeca4778362e8c0dd to your computer and use it in GitHub Desktop.
Save thommyhh/bb354ee726f870baeca4778362e8c0dd to your computer and use it in GitHub Desktop.
PHP: Reading DB credentials from `.my.cnf`
<?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