3

I am having an issue with trying to set environment variables in my EC2 instance and then retrieving them with php.

So I have an EC2 instance running a Bitnmai Wordpress site. I ssh's into the server and added the environment variable in /etc/environment

export VARIABLE_NAME=example_value

on the front end of things, my php to retrieve the value is:

<?php $env_var = $_ENV["VARIABLE_NAME"];

But it returns blank

I have also tried

$env_var = array('environment' => getenv("VARIABLE_NAME"));

But that just returns {environment: false}

Any help would be greatly appreciated

user3239351
  • 61
  • 1
  • 6
  • You need to get in the habit of [accepting answers](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) which help you to solve your issues. You'll earn points and others will be encouraged to help you. – Jay Blanchard May 18 '17 at 18:09

2 Answers2

2

I typically set environment variables on EC2 instances in an .htaccess file. For example, here is MySQL connection information which is consumed later by a configuration file:

SetEnv DBL "mysql:dbname=rocknroll;host=rocknroll.local;port=3306"
SetEnv DB_USER "Elvis"
SetEnv DB_PASS "1amth3K1ng"

Then in my PHP file(s) I do this:

define('DBL', getenv('DBL'));
define('USER', getenv('DB_USER'));
define('PASS', getenv('DB_PASS'));

This uses PHP's getenv() function and makes the variables easy to retrieve.

Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
  • Thank you for the response! I will give this a try. I am a total newbie when it comes to this server side configuration stuff. Question though. Where would the .htaccess file be located on my EC2 instance? Is it in my wordpress directory? – user3239351 May 18 '17 at 18:09
  • So I was able to find the .htaccess and I added my environment variable using the above method that was mentioned above; however, it is still not working. I tried restarting apache for the environment variable to take place but then the environment variables disappear from the .htaccess file. Does anyone have any insight on this? – user3239351 May 18 '17 at 19:22
  • Disappears from the .htaccess file? – Jay Blanchard May 18 '17 at 19:40
1

So when I would restart the apache server, it would overwrite the .htaccess file to its default state and all my changes would be gone.

So I found a solution that works for what I need. I added the environment variables into the wp-config.php file define('ENV_VARIABLE','VALUE'); Then I was able to use that value by $value = ENV_VARIABLE;

Thanks for all of the help!

user3239351
  • 61
  • 1
  • 6
  • What I don't understand is why Apache is overwriting the .htaccess file on restart. That makes no sense. In addition, you don't have to restart Apache when you make changes to an htaccess file http://stackoverflow.com/questions/142559/do-you-have-to-restart-apache-to-make-re-write-rules-in-the-htaccess-take-effec – Jay Blanchard May 19 '17 at 12:46