如何在 Azure Linux 应用服务提供的 PHP 代码中使用 Mysql 连接字符串

How to use Mysql Connection String inside PHP code which is served by Azure Lunix App Service

我正在尝试将 Wordpress 托管到 Azure lunix 应用服务。

我为 MySQL 创建了一个 Azure 数据库,然后我从连接字符串屏幕获取了 Web 应用程序连接字符串。

连接字符串格式为

Database={your_database}; Data Source={data_source}; User Id= {user_id}; Password={your_password}

然后我创建了一个基于 Linux 的应用程序服务,并将 MySQL 连接字符串添加到其配置中。

然后我在 wp-config.php 中使用这段代码从 PHP 环境变量 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);
}

如果您使用的是 windows 应用程序服务,则该代码有效。但是,如果您使用的是 Linux 应用程序服务,您将收到此警告并且 wordpress 将无法工作

Warning: mysqli_real_connect(): (HY000/2002): No such file or directory in /wordpress/wp-includes/wp-db.php on line 1452

我使用此代码创建了一个 php 信息页面

<?php
phpinfo();
?>

我确定 PHP 环境变量已加载,但我需要一种访问它的方法。

如何在 PHP 代码中访问该连接字符串?

经过很长时间的搜索,我发现唯一的方法是使用 getenv 函数。

wp-config.php 中的最终代码为:

$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);