Skip to content

Instantly share code, notes, and snippets.

@jonasbjork
Created December 4, 2012 09:50
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jonasbjork/4202267 to your computer and use it in GitHub Desktop.
Save jonasbjork/4202267 to your computer and use it in GitHub Desktop.
PHP code that parses wp-config.php and returns mysql command for connection to the database.
<?php
/**
* Get database connection string from a wp-config.php file.
*
* Usage: php db.php /var/www/wp-config.php
*
* Output: mysql -h DB_HOST -u DB_USER -pDB_PASSWORD DB_NAME
*
* @author Jonas Björk <jonas.bjork@me.com>
* @date 2012-12-04
* @version 1.0
* @license http://opensource.org/licenses/GPL-2.0 The GNU General Public License (GPL-2.0)
*/
if ($argc > 1) {
$file = $argv[1];
} else {
print "\nYou can specify which wp-config.php file with:\ndb.php [PATH_TO_wp-config.php]\n";
print "Trying to parse /var/www/wp-config.php now.\n\n";
$file = '/var/www/wp-config.php';
}
$fh = @fopen($file, 'r');
if ($fh) {
while (!feof($fh)) {
$data[] = fgets($fh);
}
fclose($fh);
foreach ($data as $line) {
if (preg_match('/define.*(DB_USER|DB_HOST|DB_PASSWORD|DB_NAME)/', $line)) {
$conf[] = $line;
}
}
if (@count($conf) < 3) {
print "Could not find constants DB_HOST, DB_USER, DB_PASSWORD, DB_NAME\n";
exit;
}
$php_code = implode($conf);
eval($php_code);
printf ("\nmysql -h %s -u %s -p%s %s\n\n", DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
} else {
printf("Could not open file %s for reading.\n", $file);
}
@victorjonsson
Copy link

How clever :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment