1

On CentOS, I'm trying to pass an environment variable to a PHP script.

I've created this file, test.php:

<?php print_r($_ENV);

When I run this command:

DB=mysql php test.php

I get the following output:

Array
(
)

What did I miss?

5
  • Something in PHP, because even without your extra DB environment variable, there should be plenty of them. Commented Sep 17, 2014 at 15:59
  • 1
    @derobert Did you vote to move this to Stackoverflow? I specifically chose to ask it here because I thought it would be closed on Stackoverflow as off-topic, because it's about environment variables on Linux! Commented Sep 17, 2014 at 16:01
  • 1
    Yes. Most likely, you need to fix your setting of variables_order and/or use getenv(). Accessing the Unix environment variables (from a particular programming language, i.e., PHP) should be on-topic on SO... Though I wouldn't be surprised if there is a duplicate there. Commented Sep 17, 2014 at 16:03
  • @derobert Thank you, I just checked variables_order and noticed that it does not populate $_ENV by default, I did not know that! I thought this config was only about populating the $_REQUEST variable (and global variables in previous versions of PHP). Commented Sep 17, 2014 at 16:08
  • Indeed, I would have noticed the dup if only I knew that $_ENV should not be empty by default! Thanks for your help anyway, much appreciated. Commented Sep 17, 2014 at 16:10

2 Answers 2

8

Check your variables_order php.ini variable. It has to contain E for $_ENV to be populated. You can also do:

$ DB=whatever php -d variables_order=E -r 'echo $_ENV["DB"];'
whatever

Alternatively, you can use getenv() which will work regardless of the value of variables_order.

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

Comments

2

Use getenv function:

$ cat test.php
<?php
    print_r(getenv('DB'));
?>

$ DB=msql php test.php
mysql

Comments

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.