Skip to content

Instantly share code, notes, and snippets.

@jonasbjork
Created December 4, 2012 09:50
Show Gist options
  • Save jonasbjork/4202267 to your computer and use it in GitHub Desktop.
Save jonasbjork/4202267 to your computer and use it in GitHub Desktop.

Revisions

  1. jonasbjork created this gist Dec 4, 2012.
    49 changes: 49 additions & 0 deletions db.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,49 @@
    <?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 <[email protected]>
    * @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);
    }