I am using a Linux EC2 instance on Amazon Web Services where I set up the instance-id as an environment variable by executing
export EC2_INSTANCE_ID=$(curl http://169.254.169.254/latest/meta-data/instance-id)
When I try to retrieve the data from the variable in php using $_ENV['EC2_INSTANCE_ID'] or getenv("EC2_INSTANCE_ID") I get an error:
Undefined index: EC2_INSTANCE_ID
(This error comes from $_ENV['...'], getenv() simply does not return the value of the variable.)
I already set up environment variables in the php.ini by setting variables_order = "EGPCS".
When I run printenv in the command line I get EC2_INSTANCE_ID=i-039......
I restarted apache by using service httpd restart after setting the environment variable.
So why is php not fetching the variable?
If you execute export VARNAME=value in the shell, as you suggest in your question, then a PHP program running in a web server will not be able to read it. If you use Apache for example, then you will need to set that variable in the Apache configuration for that particular virtual host.. something like:
<VirtualHost ser.ver:80>
SetEnv VARNAME value
</VirtualHost>
Then, a PHP program on that server will be able to read that variable with getenv() or $_ENV as you expect.
What you describe would only work if your PHP program is executed as client program in your computer:
$ export VARNAME=value
$ cat "<?php echo getenv('VARNAME'); ?>" > test.php
$ php test.php
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With