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

0

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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?
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?
Disappears from the .htaccess file?
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!

1 Comment

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 stackoverflow.com/questions/142559/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.