Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set and retrieve environment variables using PHP on EC2 instance

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

like image 208
user3239351 Avatar asked Feb 28 '26 09:02

user3239351


1 Answers

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.

like image 89
Jay Blanchard Avatar answered Mar 03 '26 04:03

Jay Blanchard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!