问题
I'm trying to host Wordpress to Azure lunix App service.
I created a Azure Database for MySQL, then I got the web app connection string from the connection strings screen.
The connection string format is
Database={your_database}; Data Source={data_source}; User Id= {user_id}; Password={your_password}
Then I created a Linux based app service and added the MySQL connection string to its configuration.
Then I used this code in wp-config.php
to get the Database connection string form the PHP environment variable MYSQLCONNSTR_bridgesConnection
<?php
$connectstr_dbhost = '';
$connectstr_dbname = '';
$connectstr_dbusername = '';
$connectstr_dbpassword = '';
foreach ($_SERVER as $key => $value) {
echo $key ;
if (strpos($key, "MYSQLCONNSTR_bridgesConnection") !== 0) {
continue;
}
$connectstr_dbhost = preg_replace("/^.*Data Source=(.+?);.*$/", "\\1", $value);
$connectstr_dbname = preg_replace("/^.*Database=(.+?);.*$/", "\\1", $value);
$connectstr_dbusername = preg_replace("/^.*User Id=(.+?);.*$/", "\\1", $value);
$connectstr_dbpassword = preg_replace("/^.*Password=(.+?)$/", "\\1", $value);
}
That code works if you are using windows App service. But If you are using Linux App service you will get this warning and the wordpress won't work
Warning: mysqli_real_connect(): (HY000/2002): No such file or directory in /wordpress/wp-includes/wp-db.php on line 1452
I created a php info page using this code
<?php
phpinfo();
?>
I'm sure that the PHP environment variable is loaded but I need a way to access it.
How to access that connection string in PHP code?
回答1:
After very long search I found the only way to do that is to use getenv
function.
The final code in wp-config.php
would be:
$connectstr_dbhost = '';
$connectstr_dbname = '';
$connectstr_dbusername = '';
$connectstr_dbpassword = '';
$value = getenv('MYSQLCONNSTR_bridgesConnection');
$connectstr_dbhost = preg_replace("/^.*Data Source=(.+?);.*$/", "\\1", $value);
$connectstr_dbname = preg_replace("/^.*Database=(.+?);.*$/", "\\1", $value);
$connectstr_dbusername = preg_replace("/^.*User Id=(.+?);.*$/", "\\1", $value);
$connectstr_dbpassword = preg_replace("/^.*Password=(.+?)$/", "\\1", $value);
// ** MySQL settings - You can get this info from your web host ** //
/** The name of the database for WordPress */
define('DB_NAME', $connectstr_dbname);
/** MySQL database username */
define('DB_USER', $connectstr_dbusername);
/** MySQL database password */
define('DB_PASSWORD', $connectstr_dbpassword);
/** MySQL hostname : this contains the port number in this format host:port . Port is not 3306 when using this feature*/
define('DB_HOST', $connectstr_dbhost);
来源:https://stackoverflow.com/questions/56007265/how-to-use-mysql-connection-string-inside-php-code-which-is-served-by-azure-luni