Wordpress Hack » Reading MySQL username & password from wp-config.php
A few months ago I was working on a prototype Wordpress plug-in that generated graphs using GNUPlot. To do this it had another script embedded at the end of the file which dumped data from the Wordpress database and produced graphs as images for the output.
The problem is that the GNUPlot section of the script is referred to directly my an "img" XHTML tag and is not loaded by Wordpress itself; it does not have access to the Wordpress database configuration.
To workaround this I wrote the following section of code, it opens the "wp-config.php" file and parses out anything matching the pattern "define( name, value )" into a $config variable. Immediately afterwards it attempts to connect to MySQL using these details.
Bit of a hack, but it was the only nice way I could see to do it and keep the plug-in simple & configuration free.
-
-
// HACK Read wp-config.php for the Database username/password, including it wouldnt work
-
if ( $handle ) {
-
$content = '';
-
}
-
if ( preg_match_all("/define\s*\(\s*'(.*?)'\s*,\s*'(.*?)'\s*\);/", $content, $matches, PREG_SET_ORDER) ) {
-
for ( $i = 0; $i <count($matches); $i++ ) {
-
$name = $matches[$i][1]; $value = $matches[$i][2];
-
$config[$name] = $value;
-
}
-
}
-
}
-
-
-
$link = mysql_connect( $config['DB_HOST'], $config['DB_USER'], $config['DB_PASSWORD']) or die ("Can't connect!");