[英]How to use Mysql Connection String inside PHP code which is served by Azure Lunix App Service
我正在嘗試將Wordpress托管到Azure lunix App服務。
我創建了一個用於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 App服務,該代碼可以正常工作。 但是,如果您使用的是Linux App服務,則會收到此警告,並且wordpress將無效
警告:mysqli_real_connect():( HY000 / 2002):第1452行的/wordpress/wp-includes/wp-db.php中沒有此類文件或目錄
我使用此代碼創建了一個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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.