Azure App Service: How to read and parse connection strings via PHP
On Azure App Service, developers have the ability to configure the connection strings as key-value pair under App Settings section. Here is a sample screenshot:
At runtime, Azure App Service retrieves this key-value pair for you and makes them available to your hosted application. These are provided to the web app as Environment Variables.
Here is a good article on how to these work internally: How Application Strings and Connection Strings Work
Here is a sample code on how to read the app settings in PHP
<?php
$connstr = getenv("MYSQLCONNSTR_MySqlDB");
//Parse the above environment variable to retrieve username, password and hostname.
foreach ($_SERVER as $key => $value)
{
if (strpos($key, "MYSQLCONNSTR_") !== 0)
{
continue;
}
$hostname = preg_replace("/^.*Data Source=(.+?);.*$/", "\\1", $value);
$username = preg_replace("/^.*User Id=(.+?);.*$/", "\\1", $value);
$password = preg_replace("/^.*Password=(.+?)$/", "\\1", $value);
break;
}
echo "Server Name: ".$hostname."</br>";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL");
echo "<br>Connected to DB server successfully</br>";
//select a database to work with
$selectDb = mysql_select_db("db_name",$dbhandle) or die("Could not select database");
//execute the SQL query and return records
$sqlQuery = mysql_query("SELECT * FROM Table") or die("Could not query database");
mysql_close($dbhandle);
?>
Summary
The sample code is a way to get started on how to retrieve the connection strings at runtime in PHP. I have used the above sample to read from a database and display it on a page. The project is hosted on GitHub. See here: https://github.com/kaushalp/Problematique/edit/master/ProblematicMvc/client.php