Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting WordPress database name/username/password with PHP

Tags:

oop

php

wordpress

I'm writing a WordPress plug-in and need to read the database name, username, and password (In order to do a sql dump). Is this possible?

Thanks-

like image 432
Yarin Avatar asked Feb 28 '11 16:02

Yarin


2 Answers

Yes, they are defined in wp-config.php

  1. Database Name: DB_NAME
  2. Database User: DB_USER
  3. Database password: DB_PASSWORD
  4. Database Host: DB_HOST

They are define. See you wp-config.php in the root directory of Wordpress

like image 79
keatch Avatar answered Oct 15 '22 01:10

keatch


Wordpress has some fairly goofy stuff going on throughout its OO code, this isn't the first one I've encountered as we dig deeper into the internals with each successive project at Moxune. See WP_User::__set doesn't persist custom fields as it claims.

The goofiness I refer to here of course is that something like the table prefix, aka wpdb::prefix is a public member variable, however things like dbname, dbpassword, and dbhost are protected and there are no public accessor methods.

I'm sure one of the Wordpress core devs will try to argue some rationale for it, but in the meantime may as well use some good 'ol OO to cope. My suggestion, a decorator.

class SaneDb
{
    private $_oDb;

    public function __construct(wpdb $oDb)
    {
        $this->_oDb = $oDb;
    }

    public function __get($sField)
    {
        if($sField != '_oDb')
            return $this->_oDb->$sField;
    }

    public function __set($sField, $mValue)
    {
        if($sField != '_oDb')
            $this->_oDb->$sField = $mValue;
    }

    public function __call($sMethod, array $aArgs)
    {
        return call_user_func_array(array($this->_oDb, $sMethod), $aArgs);
    }

    public function getDbName() { return $this->_oDb->dbname;     }
    public function getDbPass() { return $this->_oDb->dbpassword; }
    public function getDbHost() { return $this->_oDb->dbhost;     }
}

Then atop your plugin code (functions.php) setup a global in similar vein to wpdb.

global $sanedb;
$sanedb = new SaneDb($wpdb);

From there, just use $sanedb within your plugin instead of $wpdb.

Lastly, getting ahold of the database name et al.

$sanedb->getDbName();
like image 26
quickshiftin Avatar answered Oct 15 '22 00:10

quickshiftin