Environment Variables in Apache and Xampp
Wall Script
MailxEngine
Sunday, August 08, 2021

Environment Variables in Apache and Xampp

Few days back one of my friend's project database credentials got exposed. After some investigation, we realized that it is because of the .git config commit. I would recommend configuring your sensitive credentials with operating system environment variables. This way you can protect information from the code base. This post will explain how to set up an environment variable for an Apache web server.

Environment Variables in Apache and Xampp


Apache Config Folder
If you have Apache installed, go to the following directory.
cd /etc/apache2/sites-available

Take Config File Backup
Duplicate the original configuration file with different name. You can revert if anything wrong.
cp 000-default.conf 000-default.conf.back

Edit 000-defualt.conf
You have to modify the default conf file for environment configuraiton. User nano or vi editor.
vi 000-default.conf

Configure Enviroment Variables
Modify the file and include all of you sensitive information like database, SMTP and AWS credentials.
<VirtualHost *:80>
SetEnv DB_USERNAME Your_Username
SetEnv DB_PASSWORD Your_Password
SetEnv SMTP_USERNAME Your_SMTP_Username
SetEnv SMTP_PASSWORD Your_SMTP_Password
</VirtualHost>

Restart Apache Server
Save the above file and restart your Apache server.
$/etc/init.d/apache2 restart

XAMPP
If you are using XAMPP, it has a different config settings.

XAMPP Location
Got to XAMPP httpd configuration location.
cd /opt/lampp/etc

Take Backup
Copy the httpd.conf with different name.
cp httpd.conf httpd.conf.back

Edit httpd.conf
You have to modify the default conf file for environment configuraiton. User nano or vi editor.
vi httpd.conf

Configure Enviroment Variables
You can include SetEnv values.
SetEnv DB_USERNAME Your_Username
SetEnv DB_PASSWORD Your_Password
SetEnv SMTP_USERNAME Your_SMTP_Username
SetEnv SMTP_PASSWORD Your_SMTP_Password

Restart XAMPP Server
Save the above file and restart your XAMPP server.
$/opt/lampp/lampp restart
PHP Configuration
You can read evniroment variables using getenv method.
<?php
$DB_USERNAME = getenv('DB_USERNAME');
$DB_PASSWORD = getenv('DB_PASSWORD');
//SMTP credentials
$SMTP_USERNAME = getenv('SMTP_USERNAME');
$SMTP_PASSWORD = getenv('SMTP_PASSWORD');
$SMTP_HOST = getenv('SMTP_HOST');


function getDB()
{
$dbhost = 'localhost';
$dbuser = $DB_USERNAME;
$dbpass = $DB_PASSWORD;
$dbname = 'Your_Database_Name';
$dbConnection = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$dbConnection->exec("set names utf8");
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $dbConnection;
}
?>
web notification

0 comments:

Make in India